Memory leak in child process. How to handle memory in child processes

170 views Asked by At

I'am writting a terminal and using the following function to execute a command :

void    execute_input(t_list *node, char **envp)
{
    int     pid1;
    int     status;

    if (ft_lstsize(node) > 1)
        command_chain(node);
    else if (is_builtin(node))
        execute_builtin(node);
    else
    {
        get_data()->executing_cmd = 1;
        pid1 = fork();
        if (pid1 == 0)
        {
            if (!access(node->token[0], X_OK))
                node->path = node->token[0];
            execve(node->path, node->token, envp);
            exit(errno);
        }
        waitpid(pid1, &status, 0);
        if (WIFEXITED(status))
            get_data()->exit = WEXITSTATUS(status);
        get_data()->executing_cmd = 0;
    }
}

node->path and node->token were dynamically allocated in the parent.

When my execve returns -1 because he was unable to execute the program, I will have some weird memory leaks that I can't solve.

I don't know how to approach this situation. I have tried freeing the memory in the child process after execve but that will result in invalid free.

How should handle in the child process the memory that was allocaed in the parent process?

1

There are 1 answers

9
zwol On

If execve fails, you're going to exit the child process immediately [technically you should be doing this with _exit instead of with exit, but don't worry about that right now].

When you exit the child process, the operating system deallocates all the resources allocated to it, including everything allocated by malloc.

Therefore, it is unnecessary to free anything explicitly in the child process.