简体   繁体   English

C和linux中的虚拟地址分配

[英]virtual address assignment in C and linux

In the program given below virtual address for both process is same. 在下面给出的程序中,两个过程的虚拟地址是相同的。 I understood the reason for global variables but could not understand for local variables. 我了解全局变量的原因,但不了解局部变量。

how is virtual addresses assigned to local variables before running? 在运行之前如何将虚拟地址分配给局部变量?

int main()
{
  int a;
  if (fork() == 0)
  { 
     a = a + 5; 
    printf(“%d,%d\n”, a, &a); 
  }
  else 
  { 
     a = a –5;
    printf(“%d, %d\n”, a, &a); 
   } 
}

Virtual addresses are... virtual. 虚拟地址是...虚拟的。 That means a same virtual address from two different processes (like a parent process and its child process) points to two different physical addresses. 这意味着来自两个不同进程(例如父进程及其子进程)的相同虚拟地址指向两个不同的物理地址。

While compiling, the compiler decides to use either the stack or a register for local variables. 在编译时,编译器决定使用堆栈或寄存器来存储局部变量。 In this case, the stack. 在这种情况下,堆栈。

It also decides where in the (virtual) address space to place the stack. 它还决定在(虚拟)地址空间中放置堆栈的位置。

So for both processes the stack starts in the same (virtual) address. 因此,对于这两个进程,堆栈都从相同的(虚拟)地址开始。 And since the flow of this specific program is rather deterministic, the stack frames look exactly the same for both processes, resulting in the same offset in the stack for 'a'. 而且由于此特定程序的流程是确定性的,因此两个过程的堆栈帧看起来完全相同,从而导致堆栈中“ a”的偏移量相同。

Whatever the address of a was before the fork, it must surely be the same after the fork, so it necessarily is the same in the two processes, since their addresses for a are both equal to the same thing. 的任何地址a是叉之前,肯定是后叉一样的,所以它一定是在这两个过程是相同的,因为他们的地址, a都等于同样的事情。 In most implementations, the address of a is derived by adding an offset (determined by the compiler) to the content of the stack pointer. 在大多数实现中,地址a是通过将偏移量(由编译器所确定的)的堆栈指针的内容导出的。 The content of the stack pointer is duplicated by fork. 堆栈指针的内容由fork复制。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM