在UNIX分支之后,指向动态分配的内存的指针会发生什么情况? [英] what happens to pointers to dynamically allocated memory after a UNIX fork?

查看:51
本文介绍了在UNIX分支之后,指向动态分配的内存的指针会发生什么情况?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请澄清在fork()之后使用指针会发生什么情况.

Someone please clarify what happens with pointers after a fork().

据我了解,指向堆栈上或静态分配的任何内容的指针都是相对于堆栈/数据段寄存器的,因此可以在派生期间完全复制它们.

As I understand it, pointers to anything on the stack or statically allocated are relative to the stack/data segment registers, so copying them exactly during a fork is OK.

但是,如果我在分叉之前malloc()发生了什么?例如:

However, what happens if I malloc() something before forking? for example:

void* p = malloc(64);
// put something in *p;
fork();

// what happens to p and the memory i allocated here?

我正在考虑的可能性:

  1. * p被复制到堆的其他部分,p被更新以反映新复制的位置.

  1. *p is copied to some other part of the heap, p is updated to reflect the newly copied location.

p仍指向原始.如果有孩子自由奔跑(p);家长可能无法访问它.

p still points to the original. if any child runs free(p); the parent may be unable to access it.

p仍然指向原始数据,但是子进程没有访问/管理内存的权限.

p still points to the original data, but the child process does not have rights to access/manage the memory.

其中哪一个是正确的?

推荐答案

分叉时,子进程成为其父进程的副本.这包括任何动态分配的内存.因此,内存将被复制.指针地址将保持不变(记住,副本不会更改数据吗?),这是通过虚拟寻址实现的.不要忘记在父进程和子进程中都调用 free .

When forking, child process becomes a copy of its parent. That includes any dynamically allocated memory. So the memory will be copied. Pointer address will stay the same (copy doesn't change data, remember?), which is achieved by virtual addressing. Don't forget to call free in both parent and child processes.

这篇关于在UNIX分支之后,指向动态分配的内存的指针会发生什么情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆