使用字符串数组时的总线错误10 - C.

时间:2013-10-24 05:13:57

标签: c arrays string bus

我有一个程序在选项参数(-r,-d等)之后接受非选项参数(来自命令行),并将每个非选项参数插入到数组中。可以输入的非选项参数的最大数量为25。

但问题是,当我运行程序时出现“总线错误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

我收到公交车错误。

2 个答案:

答案 0 :(得分: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
}

答案 1 :(得分: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

最重要的是,如果argvmain的第二个参数,你可以复制其中的指针(不需要复制字符串内容),如buf_name[i] = argv[optind+i];