有人問我,在父進程中Malloc的內存空間,若是fork()後,到了子進程中,會不會在copy一份出來?仍是共用一個空間?看程序:
void main()
![](http://static.javashuo.com/static/loading.gif)
{
char *p;
![](http://static.javashuo.com/static/loading.gif)
p = malloc(10);
![](http://static.javashuo.com/static/loading.gif)
strcpy(p,
"ccc");
![](http://static.javashuo.com/static/loading.gif)
printf(
"p=%p %s\n", p, p);
if (fork() == 0)
![](http://static.javashuo.com/static/loading.gif)
{
![](http://static.javashuo.com/static/loading.gif)
strcpy(p,
"ccc3333");
![](http://static.javashuo.com/static/loading.gif)
printf(
"child p=%p %s\n", p,p);
![](http://static.javashuo.com/static/loading.gif)
sleep(10);
![](http://static.javashuo.com/static/loading.gif)
printf(
"child p=%p %s\n", p,p);
![](http://static.javashuo.com/static/loading.gif)
}
else
![](http://static.javashuo.com/static/loading.gif)
{
![](http://static.javashuo.com/static/loading.gif)
sleep(3);
![](http://static.javashuo.com/static/loading.gif)
strcpy(p,
"ccc444");
![](http://static.javashuo.com/static/loading.gif)
printf(
"father p=%p %s\n", p,p);
![](http://static.javashuo.com/static/loading.gif)
}
![](http://static.javashuo.com/static/loading.gif)
free(p);
![](http://static.javashuo.com/static/loading.gif)
}
執行結果:
[zyx@ymserver src]$ ../bin/t1
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的地址都是一個地方呢?那是由於這個地址是一個虛擬的地址,每一個進程都擁有本身的虛擬地址空間,不一樣進程的相同地址空間其實在物理上是不一樣的地址塊!
注:上面的程序沒有加上錯誤判斷,測試程序而已,不用加了。