pudumaster
pudumaster

Reputation: 181

Bus error 10 when working with string array - C

I have a program that takes the non-option arguments (from the command line) after an option argument (-r, -d etc.) and inserts each non-option argument into an array. The maximum number of non-option arguments that can be typed in is 25.

But the problem is that when I run the program is gives a 'Bus Error 10" error and I'm not sure why. I've looked at so many posts with similar problems but can't seem to fix mine.

The code is:

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
}
}

When I run it like this:

./program -r arg1 arg2

I get a bus error.

Upvotes: 1

Views: 1562

Answers (2)

your code

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

is completely wrong. At least it should be

 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;
 }

but even the above is probably wrong. Perhaps you want to use strdup.

And most importantly if the argv is the second argument to main you can copy the pointers in it (don't need to copy the string contents) like buf_name[i] = argv[optind+i];

Upvotes: 0

Rohan
Rohan

Reputation: 53366

Added some comments ...

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
}

the correct code would be:

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
}

Upvotes: 1

Related Questions