This code makes a segmentation fault:
int main(int argc, char *argv[]){
int *n;
*n = atoi(argv[1]);
printf("n: %d \n", *n);
return 0;
}
while this works:
int main(int argc, char *argv[]){
int *n;
*n = atoi(argv[1]);
pid_t pid = fork();
if (pid == 0)
return 0;
else
printf("n: %d \n", *n);
return 0;
}
Why the second with the fork works? I know that after int *n
, I should allocate space for an int
with a malloc()
, but using the fork()
seems to do this automatically.
edit: Now I understand Undefined behavior :) But now I'm asking: what is the cause in this specific case?
It does not work. (Or more precisely, you have undefined behavior)
1) The fork is just hiding the segfault, because you are not checking the exit code of the child process.
2) The allocation of memory is not automatic -- ever !
You are just writing to a random location, and you may just be "lucky" that in the second version that the random location is within your process space.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With