【问题标题】:Parent and child has same address of a varibale but value differs [duplicate]父母和孩子具有相同的变量地址但值不同[重复]
【发布时间】:2014-08-07 07:26:40
【问题描述】:

我知道父母和孩子有不同的地址空间,但是当我运行下面的代码并检查父母和孩子中变量的地址时,结果是相同的。好像两个变量名都用于相同的内存位置,为什么子级的值变化没有反映在父级中。

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>

int main()
{

    int turn = 0;
    if (fork() == 0)
    {
            turn = 10;
            printf("Child Turn: %d\n", turn);
            printf("Child Address of turn: %p\n", &turn);
            exit(0);
    }
    else
    {
            sleep(2);
            printf("Parent Turn: %d\n", turn);
            printf("Parent Address of turn: %p\n", &turn);
    }

return 0;
}

输出是:

儿童回合:10

轮到子地址:0xbfc1830c

父轮数:0

转的父地址:0xbfc1830c

如果两者具有相同的地址,为什么值不同。或者是类似的东西

如果我们有两个盒子,一个命名为父级,一个命名为子级。

两个方框都包含数字 1 到 10。

所以在子框中我们也有说数字 5,

在父框中我们也有数字 5。

数字相同,但在不同的盒子里。

与上述情况类似,地址是相同的 0xbfc1830c,但在不同的进程地址空间中。是这样吗。

【问题讨论】:

    标签: c unix process


    【解决方案1】:

    这是因为virtual memory。这两个进程的变量都在同一个虚拟地址上,但当然不在同一个物理地址上。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-12
      • 2015-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-14
      相关资源
      最近更新 更多