2012-02-27 46 views
2

所以我在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() 
+3

你的問題不在Linux上編譯 - 它是與你正在寫入崩潰的程序。 – Perry 2012-02-27 18:11:33

回答

4

你是不是從strtok在循環的最後一次迭代返回檢查NULL ...所以strtok可以返回NULL,但你仍然可以通過在token指針NULL值到sprintf

更改您的while循環以下幾點:

while(token = strtok(NULL, delimiter)) sprintf(bigBuffer[++count], "%s", token); 

這樣,你可以從不NULL指針傳遞給strtok因爲while循環NULL終場前檢查將強制執行token總是有當有效值以它作爲參數調用sprintf

+0

非常感謝,解決了我的問題。但是,你知道它爲什麼在Windows中運行,但不是在Linux中運行,或者只是C在不同系統上運行方式不同的情況之一 – cpowel2 2012-02-27 18:13:28

+2

它實際上不能在Windows上「工作」......你只是很幸運,不會崩潰......這就是爲什麼他們稱之爲取消引用NULL指針**未定義的行爲** ......您可能會崩潰,或者可能會發生一些更加邪惡的事情,當一些其他神祕值會讓您感到頭痛時在內存中被破壞,你不知道爲什麼:-) – Jason 2012-02-27 18:14:50

+0

你可以改變while循環爲:while((token = strtok(NULL,delimiter)))',它會正常工作。 – 2012-02-27 18:15:07

0

您應該詢問gdb以瞭解程序崩潰的完整追溯。事實上,你不知道它在哪裏崩潰,意味着你沒有要求它完整的追溯,這是很重要的。