No segmentation failure with plug

This code causes a segmentation error:

int main(int argc, char *argv[]){ int *n; *n = atoi(argv[1]); printf("n: %d \n", *n); return 0; } 

while it 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 does the second one work with the plug? I know that after int *n I have to highlight a space for int with malloc() , but using fork() seems to do it automatically.

edit: Now I understand the behavior of Undefined :) But now I ask: what is the reason for this particular case?

+5
source share
4 answers

This does not work. (Or rather, undefined behavior)

1) The plug simply hides segfault because you are not checking the exit code of the child process.

2) Memory allocation is not automatic - never!

You just write a random location, and you might just be “lucky” that in the second version, the random location is within your process space.

+6
source

Both code snippets cause undefined behavior , courtesy of

  • using uninitialized and invalid memory *n
  • (possibly) using uninitialized and invalid argv[1] memory (if argc not >=2 )

Segmentation error is one of the many side effects of UB. In the case of UB, a seamless scenario also works.

Why does the second one work with the plug?

This has nothing to do with the presence (or absence fork() UB fork() . TL ;. DR

but using fork () seems to do it automatically.

Visual data can be misleading. Do not invest your money in UB.

+4
source

Since n not initialized and therefore points to an unknown memory address, you invoke undefined behavior. This may cause a crash (as in the first example), or it may not be so (as in the second example).

In such a situation, simply adding an unused variable can cause a program to crash, which was not before, or vice versa.

Allocate memory for n and you will not have this problem.

Edit:

The fact that works ./test 100 works when you run the second program, no matter how many times, this is a matter of luck. The fact that you added the fork call (in this case) just changed the way memory was allocated in order for it to work. You can later select the printf call for additional debugging, and suddenly it will crash again.

Adding a fork call does not automatically highlight a space.

The only way to prevent the failure is to allocate memory for n and ensure that argc is at least 2, so that argv[1] points to some value.

+3
source

it happens that you do not see segfault, as when fork starts and returns 0, your code never runs printf ("% d", *n)

Segmentation is allocated when you try to access a memory cell that is not allowed, so the solution is designed to assign ana memory through the malloc or calloc functions, otherwise the problem remains. Try the following:

  n=malloc(sizeof(int)); *n=atoi(argv[1]); 

Hello

0
source

All Articles