| shazlin (27) | |||||||
|
In my program, the parent create processes and the child compute the sum The problem is the parent code so for example if going to computer 1 2 3 4 5 it going to add 1 and 2 first and then 3 and 4 and then 5 and 0(created) There have two for loops, when it finish the inner for loop once the output is alright, but it goes into twice time the output go weird. also it works fine with argument less than 5(1 2 3 4) Parent code
child code
| |||||||
|
Last edited on
|
|||||||
| ne555 (4039) | |
Please indent your codeargv[argc] = "0"; is out of bounds
| |
|
|
|
| kbw (5374) | |
|
Your indentation doesn't make your code easy to follow. Should you be writing into argv? | |
|
|
|
| Cubbi (1572) | ||||
argv is perfectly writeable and argv[argc] = "0"; is not out of bounds (the size of argv is argc+1), that's not the problem here, per se, the problem is that the arrays pointed to by the pointers in argv are not big enough to fit the results of your additions:When you added 3 and 7, you got 10 from the child, and you executed this line:
your n was 0, so you wrote the three bytes '1', '0', and '\0' into the memory pointed to by argv[1] But your program was called with argv[1] = "1", with only two bytes to spare, so the last null was written who knows where. It appears that the C runtime that called your main(), set the pointers stored in argv pointing at subsequent locations of the same array, so that '\0' actually overwrote the character in argv[2]. On the next loop, you wrote "5" into argv[2], which overwrote that null with the five. So now you have:
That's why when you printed argv[1] as a string, you got 105. PS: as gcc rightfully complained, your execl() call is wrong: the last argument must be (char*)0, not just 0.
| ||||
|
Last edited on
|
||||
| ne555 (4039) | |
|
> (the size of argv is argc+1) ... ¿a sentinel? ¿what's the point of argc then? | |
|
|
|
| Cubbi (1572) | ||
For convenience, I guess: the sentinel is there so that argv can be passed into another execv() (according to the original man page), and the count must be there so that you don't have to loop through argv yourself. After all, in practice, everyone is using argc. | ||
|
Last edited on
|
||
| shazlin (27) | |
|
Thank You guys Learn one more thing hehe | |
|
|
|