分叉和内存分配

发布于 2024-12-03 17:42:22 字数 635 浏览 1 评论 0原文

我对算法的并行实现进行编程,该算法使用非线程安全操作。因此我使用 fork() 和 POSIX-Shared Memory,效果很好。现在问题来了。当子进程退出时,父进程动态分配的内存会发生什么? 代码看起来像这样

int compute(....) {
 //  prepare shared memory 
 pid_t child = fork(); 
 if ( child == 0 ) {
   // process the child code
   int *workspace = malloc(worksize*sizeof(int)); 
   // copy the result to Shared memory 

   free(workspace); 
   exit(0); 
 }
 // do parents work 
 wait(&status); 
 // retrieve results from shared memory 
 return 0; 
 }

问题是我不知道从哪里调用compute以及分配了哪些内存。我唯一希望我可以授予的是父级分配的内存仅在子级中只读使用。子进程分配的动态分配内存由子进程释放。 这是否会导致内存泄漏? Valgrind 说是的,但我没有办法避免这种情况。不幸的是,跟踪所有内存分配是不可能的。

I programming on a parallel implementation of an algorithm, which uses non thread-safe operations. Therefore I use fork() and POSIX-Shared Memory, which works fine. Now the questions. What happens with the dynamicaly allocated memory of the parent, when the child exits?
The code looks like this

int compute(....) {
 //  prepare shared memory 
 pid_t child = fork(); 
 if ( child == 0 ) {
   // process the child code
   int *workspace = malloc(worksize*sizeof(int)); 
   // copy the result to Shared memory 

   free(workspace); 
   exit(0); 
 }
 // do parents work 
 wait(&status); 
 // retrieve results from shared memory 
 return 0; 
 }

The problem is that I do not know from where compute is called and which memory is allocated their. The only thing I hope I can grantee is the memory that is allocated by the parent is only used read only in the child. Dynammically allocated memory which is alloced by the child is freed by the child.
Does this cause a memory leak or not? Valgrind says yes and I dont have an idea to avoid this. Tracking all memory allocations is unfortunately not possible.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

沉睡月亮 2024-12-10 17:42:22

如果代码看起来与所示完全相同,则不会产生内存泄漏。正如你所说,孩子在退出之前释放了所有内存。 valgrind 在计算分叉进程时可能会遇到一些问题。

If the code looks exactly as shown, no memory leak is produced. As you say, the child frees all its memory before exit. valgrind may have some problems accounting forked processes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文