英文:
Memory leak in child process. How to handle memory in child processes
问题
node->path
和 node->token
是在父进程中动态分配的。
当我的 execve 返回 -1 因为无法执行程序时,我会遇到一些奇怪的内存泄漏问题,我无法解决。
我不知道如何处理这种情况。我已经尝试在子进程中的 execve 后释放内存,但这会导致无效的释放。
在子进程中,应该如何处理在父进程中分配的内存?
英文:
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
得分: 2
如果 execve
失败,你将立即退出子进程 [从技术上讲,你应该使用 _exit
而不是 exit
,但现在不要担心这个]。
当你退出子进程时,操作系统会释放给它分配的 所有 资源,包括由 malloc
分配的所有内容。
因此,在子进程中不需要显式释放任何东西。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论