2013-10-24 40 views
1

我有一個程序在選項參數(-r,-d等)後面帶有非選項參數(來自命令行)並插入每個非選項參數成陣列。可以鍵入的非選項參數的最大數量是25.使用字符串數組時總線錯誤10 - C

但問題是,當我運行程序時出現'Bus Error 10'錯誤,我不知道爲什麼。看着有類似問題的很多帖子,但似乎無法修復礦山

的代碼是:

void loop_namelist(int argc, char *argv[]) 
{ 
int index = 0; 
--optind; 

char *buff_namelist[25]; //the array that the arguments are stored in 
*buff_namelist = malloc(25 * 25); //allocating some memory for the array 

while (optind < argc) //loop until no arguments left 
{ 

    strcpy(buff_namelist[index], argv[optind]); 

    ++index; //move to next index in array 
} 
} 

當我運行它像這樣:

./program -r arg1 arg2 

我乘坐公共汽車錯誤。

+0

編譯'GCC -Wall -g由source.c -o程序「(或者在編譯器中啓用所有的警告和調試信息)並學習如何使用調試器(例如'gdb')。另外,告訴我們你正在使用什麼操作系統和編譯器。 –

+1

你知道你只給指針數組中的* first *指針分配空間嗎?所以,只要'index'大於0,這是**未定義的行爲**。 – WhozCraig

+0

我正在使用gcc編譯器和那些參數,但仍然沒有。我正在使用MAC OS X. – pudumaster

回答

1

加入了一些評論...

char *buff_namelist[25]; //the array that the arguments are stored in 

//you don't need to allocate memory for array, but in this case you need to allocate 
//memory for each element in array better to do that in for loop 
*buff_namelist = malloc(25 * 25); //allocating some memory for the array 

while (optind < argc) //loop until no arguments left 
{ 
    //instead of this you should allocate and then copy; or use strdup 
    strcpy(buff_namelist[index], argv[optind]); 

    ++index; //move to next index in array 
} 

正確的代碼是:

char *buff_namelist[25]; //the array that the arguments are stored in 

while (optind < argc && argc < 25) //loop until no arguments left 
{ 

    buff_namelist[index]= strdup(argv[optind]); 

    ++index; //move to next index in array 
    optind++; //or somehow update optind 
} 
+0

非常感謝。不能相信我沒有意識到我也沒有增加optind。 – pudumaster

0

代碼

char *buff_namelist[25]; // array that the arguments are stored in 
*buff_namelist = malloc(25 * 25); //allocating memory for the array 

是完全錯誤的。至少它應該是

char* buff_namelist[25]; 
for (int i=0; i<25; i++) { 
    char* p = malloc(100); 
    if (!p) { perror("malloc"); exit(EXIT_FAILURE); }; 
    buff_name[i] = p; 
} 

但即使是上述可能是錯誤的。也許你想使用strdup

最重要的是,如果argv是第二個參數main您可以複製三分球它(不需要字符串的內容拷貝)像buf_name[i] = argv[optind+i];