Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Would 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);
        }
    }
}

Would not freeing ptr constitute a memory leak for either main.c or the other program, or is it going to be freed anyway when execve is called?

like image 524
Nick Avatar asked Dec 13 '22 19:12

Nick


1 Answers

No.

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

Edit:

User318904 brought up the case of exec() returning -1 (i.e., failure). In this case, the child process that has forked but failed to exec does, indeed technically have a memory leak, but as the usual response to a failed exec is to just exit the child process anyways, the memory will be reclaimed by the OS. Still, freeing it is probably a good habit to get into, if for no other reason than that it will keep you from wondering about it later on.

like image 122
Drew Hall Avatar answered Dec 27 '22 06:12

Drew Hall