有人问我,在父进程中Malloc的内存空间,如果fork()后,到了子进程中,会不会在copy一份出来?还是共用一个空间?看程序:
![](https://i-blog.csdnimg.cn/blog_migrate/71e1eefd64c516bfc23a59904e7a9e1b.png)
![](https://i-blog.csdnimg.cn/blog_migrate/71e1eefd64c516bfc23a59904e7a9e1b.png)
![](https://i-blog.csdnimg.cn/blog_migrate/71e1eefd64c516bfc23a59904e7a9e1b.png)
![](https://i-blog.csdnimg.cn/blog_migrate/71e1eefd64c516bfc23a59904e7a9e1b.png)
![](https://i-blog.csdnimg.cn/blog_migrate/71e1eefd64c516bfc23a59904e7a9e1b.png)
![](https://i-blog.csdnimg.cn/blog_migrate/71e1eefd64c516bfc23a59904e7a9e1b.png)
![](https://i-blog.csdnimg.cn/blog_migrate/71e1eefd64c516bfc23a59904e7a9e1b.png)
![](https://i-blog.csdnimg.cn/blog_migrate/71e1eefd64c516bfc23a59904e7a9e1b.png)
![](https://i-blog.csdnimg.cn/blog_migrate/71e1eefd64c516bfc23a59904e7a9e1b.png)
![](https://i-blog.csdnimg.cn/blog_migrate/71e1eefd64c516bfc23a59904e7a9e1b.png)
![](https://i-blog.csdnimg.cn/blog_migrate/71e1eefd64c516bfc23a59904e7a9e1b.png)
![](https://i-blog.csdnimg.cn/blog_migrate/71e1eefd64c516bfc23a59904e7a9e1b.png)
![](https://i-blog.csdnimg.cn/blog_migrate/71e1eefd64c516bfc23a59904e7a9e1b.png)
![](https://i-blog.csdnimg.cn/blog_migrate/71e1eefd64c516bfc23a59904e7a9e1b.png)
![](https://i-blog.csdnimg.cn/blog_migrate/71e1eefd64c516bfc23a59904e7a9e1b.png)
![](https://i-blog.csdnimg.cn/blog_migrate/71e1eefd64c516bfc23a59904e7a9e1b.png)
![](https://i-blog.csdnimg.cn/blog_migrate/71e1eefd64c516bfc23a59904e7a9e1b.png)
![](https://i-blog.csdnimg.cn/blog_migrate/71e1eefd64c516bfc23a59904e7a9e1b.png)
![](https://i-blog.csdnimg.cn/blog_migrate/71e1eefd64c516bfc23a59904e7a9e1b.png)
![](https://i-blog.csdnimg.cn/blog_migrate/71e1eefd64c516bfc23a59904e7a9e1b.png)
![](https://i-blog.csdnimg.cn/blog_migrate/71e1eefd64c516bfc23a59904e7a9e1b.png)
执行结果:
[zyx@ymserver src]$ ../bin/t1
p=0x8ea0008 ccc
child p=0x8ea0008 ccc3333
father p=0x8ea0008 ccc444
[zyx@ymserver src]$ child p=0x8ea0008 ccc3333
p=0x8ea0008 ccc
child p=0x8ea0008 ccc3333
father p=0x8ea0008 ccc444
[zyx@ymserver src]$ child p=0x8ea0008 ccc3333
最开始,内存块的值是ccc,地址为0x8ea0008
后来,先执行子进程的 strcpy(p, "ccc3333"); 发现,内存值变成了ccc3333
再父进程 strcpy(p, "ccc444"); 发现,内存值变成了ccc444
那么是不是子进程的值被改变了呢?不是,看最后,子进程读取的内存值还是ccc3333,就可以知道,父子进程各有一片空间。
那么为什么p的地址都是一个地方呢?那是因为这个地址是一个虚拟的地址,每个进程都拥有自己的虚拟地址空间,不同进程的相同地址空间其实在物理上是不同的地址块!