所以我在linux(Ubuntu)中使用emacs文本編輯器編寫了下面的代碼,它基本上應該將傳入的分隔符中的字符串拆分。當我跑它時segfaulted我通過GDB運行它,它給了我一個錯誤在strcpy(我沒有調用),但可能隱式在sprintf中完成。我認爲我沒有做錯任何事情,所以我啓動進入windows並通過visual studio運行它,並且它工作正常我是在Linux中編寫C的新手,並且知道問題出在While循環中,我稱之爲sprintf()(它是奇怪的,因爲循環外的調用寫入時不會導致錯誤)將令牌寫入數組。如果有人能告訴我我要出錯的地方,我將不勝感激。下面是代碼在Linux上的編譯問題
/* split()
Description:
- takes a string and splits it into substrings "on" the
<delimeter>*/
void split(char *string, char *delimiter)
{
int i;
int count = 0;
char *token;
//large temporary buffer to over compensate for the fact that we have
//no idea how many arguments will be passed with a command
char *bigBuffer[25];
for(i = 0; i < 25; i++)
{
bigBuffer[i] = (char*)malloc(sizeof(char) * 50);
}
//get the first token and add it to <tokens>
token = strtok(string, delimiter);
sprintf(bigBuffer[0], "%s", token);
//while we have not encountered the end of the string keep
//splitting on the delimeter and adding to <bigBuffer>
while(token != NULL)
{
token = strtok(NULL, delimiter);
sprintf(bigBuffer[++count], "%s", token);
}
//for(i = 0; i < count; i++)
//printf("i = %d : %s\n", i, bigBuffer[i]);
for(i = 0; i< 25; i++)
{
free(bigBuffer[i]);
}
} //end split()
你的問題不在Linux上編譯 - 它是與你正在寫入崩潰的程序。 – Perry 2012-02-27 18:11:33