gpt4 book ai didi

c - fork after malloc in parent...子进程需要释放它吗?

转载 作者:太空狗 更新时间:2023-10-29 16:41:18 28 4
gpt4 key购买 nike

头脑中问题的答案:是的,这是给学校的。不,我不能为此使用线程。是的,我在寻找答案,有些人说"is",有些人说“不是”。我也在对我的教授进行事实核查,因为我不想在别人给它打分时不公平地丢分,而且他们要求“修复”。

话虽这么说……考虑一下 Linux 系统上的这个简单的 c 程序。我 malloc 一些东西然后 fork。我将我的项目归结为确切的问题:

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>

int main( void )
{
char * args [] = { "someinvalidcommand", NULL };

// malloc before the fork (happens in parent process)
char * something = (char *)malloc(sizeof(char));

pid_t child_pid = fork();

// are there now two things that need to be freed:
// one for each process?

if(child_pid == 0) // child process
{
//free(something); // is this needed?

// execvp (it won't return if succeeded)
if(execvp(args[0], args) < 0)
{
// or do I only need to free it here?
printf("%s: No such file or directory\n", args[0]);
/*
* EDIT: Calling it here seems to fix the issue. It turns out
* that the system calls were the ones with the "still reachable"
* errors, so I guess it's not all that important that the
* memory be freed.
*
* free(something)
*/
_exit(1);
}
}
else // parent process
{
int status;
while(wait(&status) != child_pid);
if(status != 0)
{
printf("command status: %i\n", WEXITSTATUS(status));
}
}

free(something);
return 0;
}

现在这是有点令人困惑的地方。据我所知,fork 会在该特定状态(包括文本、数据等)创建父进程的精确副本。我在某处读到这包括任何 malloc'(因此,堆)。但是,我在其他地方读到它不是因为所谓的“写时复制”,但后来我在其他地方读到“写时复制”只是一种透明且无关紧要的优化。但后来我读到的最有意义的是,因为它是一个副本,所以它有自己的,好吧......一切。

但后来我记得当使用 fork() 时,无论是 malloc 的什么都会包含相同的内存地址,所以父子指向同一个东西吗?我是否也需要释放 child 的资源?是只复制指针,还是指针指向的数据也被复制?

我使用了 valgrind,当子进程退出时,它只是提示所有内存仍然可用。它到底有多“仍然可达”?它“仍然可以访问”这一事实是否回答了我的问题并说 parent 和 child 指向同一件事,而 parent 是唯一负责释放内存的人?

最佳答案

在没有调用 exec 系列的情况下,您必须 free() 它。 Parent 和 child 不指向同一个东西,因为它们是独立的进程并且不共享相同的地址空间。想象一下,如果父级 free() 执行了它,然后子级尝试访问它,那么在替代方案下会发生什么情况。

如果您确实调用了类似 execvp() 的方法,那么就像 tmyklebu 提到的那样,您的进程将被删除,而您无需执行任何操作。

“仍然可达”意味着您仍然可以引用它,但您还没有free()d它。由于您的所有内存无论如何都会在终止时得到 free()d,与您永久失去对已分配内存的跟踪的实际内存泄漏相比,这有时并不是什么大问题。 Valgrind's FAQ本身说“你的程序可能没问题——它没有释放它可能拥有的一些内存。这是很常见的,而且通常是合理的。”关于这个问题的观点各不相同——一些人说明确地释放所有东西是一种很好的形式,另一些人说它是一种毫无意义的浪费资源来完成程序终止本身将为你们做的事情。

关于c - fork after malloc in parent...子进程需要释放它吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23440132/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com