Search code examples
cprocesssegmentation-faultparentprintf

C sprintf causing a segmentation fault


I am trying to pass in arguments to the a parent file that is supposed to create a child process for each pair of arguments. The child processes will add up each pair and return their sum to the parent process. If there is an odd number of arguments passed in, I add a 0 to the end of the argv array to make it even. This keeps happening until all the arguments have been added up, and their sum is printed at the end.

Everything is working fine except when I pass in an even amount of arguments. A child process will successfully add the first two arguments and return them, but then when the parent does a sprintf, (line 58) there is always a segmentation fault.

Here is the code for both the parent and child processes (I am using pastebin so it doesn't look very cluttered here. They will expire in one day, so I could re-post them if needed):

The second file has to be called worker when it is compiled in order to be run by the first file. I am using gcc on Ubuntu 9.10

Here are a few examples on how to run the program:

gcc -o parent parent.c
gcc -o worker worker.c
./parent 1 2 3 4

(The above example will end with a segmentation fault like I explained above). The answer should be 10 because (1 + 2) + (3 + 4) = 10.

This one below will work fine though with an odd number of arguments being passed in:

./parent 1 2 3

The answer to this one should be 6.

Any help would be greatly appreciated!


Solution

  • The C standard allows one to modify the strings pointed-to by argv:

    The parameters argc and argv and the strings pointed to by the argv array shall be modifiable by the program, and retain their last-stored values between program startup and program termination.

    But it doesn't guarantee you to write past the available number of arguments in argv, which is what you are doing when you store the sum at the end of argv.

    You seem to be using argv[i] for char * variables. Why not just declare separate variables for the purpose of storing the sum? You also don't need to store "0" in argv[argc-1] if the number of numbers to sum is odd—you can easily determine that in your loop, and pass "0" to the last worker.