Will this be considered a memory leak?

Consider this pointless program:

/* main.c */ #include <stdlib.h> #include <unistd.h> int main(int argc, char **argv) { int i; for (i = 0; i < 1024; i++) { int pid = fork(); int status; if (pid) { wait(&status); } else { char *ptr = (char *)malloc(1024*sizeof(char)); char *args[2] = {"Hello, world!", NULL}; execve("/bin/echo", args, NULL); } } } 

Does ptr clear a memory leak for main.c or another program, or will it be freed up anyway when execve is called?

+4
source share
3 answers

No.

This is not a memory leak. exec*() will create a local copy of the string data in the args array, then blow off the memory image of the child process and overlay it on the memory image used by /bin/echo . Essentially, all that remains after exec () is pid.

Edit:

User 318904 examined the case of exec () returning -1 (i.e. failure). In this case, the child process that unlocked but did not execute exec does technically have a memory leak, but since the usual response to the failed exec is just the exit from the child process, the memory will be recovered by the OS. However, liberation is probably a good habit to join, if only for the reason that it will not let you not think about it later.

+10
source

When execve returns -1, yes. Otherwise, maybe.

+3
source

The allocated memory should be freed up on exec . At the end of the call, you still cannot access it.

0
source

All Articles