Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No segmentation fault with fork

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?

like image 239
joumvaer92 Avatar asked Jul 24 '15 17:07

joumvaer92


1 Answers

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.

like image 113
Soren Avatar answered Sep 21 '22 15:09

Soren