Question

I wanted to give several arguments in the command line, like:

./programName -a 103 -p argument1,argument2,argument3

Then, I wanted to create several variables with values of these arguments: one integer variable for the number just after the flag -a, one integer variable for the number of arguments just after the flag -p and one array variable with all these arguments.

It would be always the same arguments (so my code can not manage other forms of input): -a (integer) -p (a list of arguments separated with ,)

My problem is that there is a segmentation fault. After several attempts to see where it occurs (using several printf), there is a segmentation fault when the variable a = 3 (so at the flag -p). And the segmentation occurs at the line "case 'p'".

I don't understand why this code accepts the argument "-a" but not "-p". And I don't think there is an error because of my code in the "case 'p'" because the segmentation fault occurs after that (on the line "case 'p'").

I hope you'll understand my problem and thank you for your help :).

EDIT:

Thanks to Mark Wilkins and ooga for their answers. The segmentation fault was indeed due to the individual elements of the array which wasn't initialized. If some people don't know how to efficiently initialize an array of strings, check this other question, it's well explained ;) :

Initialize array of strings

Was it helpful?

Solution

One issue that would result in a segmentation fault is the use of arg_p. It is declared as an array of char*, but the individual elements of the array are never initialized. The subsequent use of it will result in accessing an uninitialized pointer:

*(arg_p[b]+c) = *(chrp+c);

OTHER TIPS

Your segfault occurs whilst assembling your argument array. Try this instead:

    arg_p[0] = chrp;
    chrp2 = strchr(argv[a+1], ',');
    int b = 1;
    while (chrp2 != NULL) {
        *chrp2 = '\0';
        arg_p[b++] = chrp2 + 1;
        chrp2 = strchr(chrp2 + 1, ',');
    }

Also note that your arg_p array is declared locally to that block and will cease to exist after that block. You may want to declare a char** arg_p pointer and malloc the space. Remember to free it at the end.

When you increment 'a' by 2, you're going to go off the end of the argv array. You only want to increment by 1 because it's indexing the words in the command line (separated by spaces) not the characters.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top