简体   繁体   English

内存中的不同程序,相同变量,相同地址

[英]Different programs, same variables, same address in memory

I have two C codes. 我有两个C代码。 test.c is test.c是

#include <stdlib.h>

int main ()
{
    int a;
    a = 5;
    return a;
}

test2.c is test2.c是

#include <stdlib.h>

int main ()
{
    int a;
    a = 6;
    return a;
}

When I run them and I check the address in memory of the "a"s with gdb I get the same address. 当我运行它们时,我用gdb检查了“ a”内存中的地址,我得到了相同的地址。 Why is this so? 为什么会这样呢?

Breakpoint 1, main () at test.c:7 7 return a; 断点1,在test.c:7的main()返回7; (gdb) print &a $1 = (int *) 0x7fffffffe1cc (gdb)打印&a $ 1 =(int *)0x7fffffffe1cc

Breakpoint 1, main () at test2.c:7 7 return a; 断点1,在test2.c:7的main()返回7; (gdb) print &a $1 = (int *) 0x7fffffffe1cc (gdb)打印&a $ 1 =(int *)0x7fffffffe1cc

The address of "a" is on the stack frame for your program. 地址“ a”在程序的堆栈框架中。 This is a virtual address, independent of where in physical memory your program is actually loaded. 这是一个虚拟地址,与程序实际加载到物理内存中的位置无关。 Therefore, it would not be surprising if both (almost identical) programs used the same address. 因此,如果两个(几乎相同)的程序都使用相同的地址就不足为奇了。

Because each application in OS is run in its own memory space. 因为OS中的每个应用程序都在其自己的内存空间中运行。

Address 0x7fffffffe1cc is not really physical address. 地址0x7fffffffe1cc不是真正的物理地址。 This is made due to security - you cannot handle other process memory directly just like that. 这是出于安全考虑-不能像这样直接处理其他进程内存。 You also cannot handle devices directly. 您也不能直接处理设备。

You can read more about that here and here 你可以在这里这里阅读更多

It is very likely that your OS is using Virtual Memory for memory management. 您的操作系统很有可能正在使用虚拟内存进行内存管理。 What this means is that addresses found within a given program are not 1:1 mapped to physical memory. 这意味着在给定程序中找到的地址未1:1映射到物理内存。 This allows for a number of things (including running multiple programs that require lots of memory by page swapping to disk). 这允许很多事情(包括运行多个需要通过页面交换到磁盘来占用大量内存的程序)。 Without virtual memory, if you were to allocate static int a rather than put it on the stack, the linker would do it's best to choose an address for it. 如果没有虚拟内存,则如果要分配static int a而不是将其放在堆栈上,则链接程序将最好为它选择一个地址。 If you then linked another program, it doesn't know what other programs may be using that address. 如果您随后链接了另一个程序,它将不知道还有哪些其他程序正在使用该地址。 Running two programs could stomp on the memory of the other program. 运行两个程序可能会占用另一个程序的内存。 With virtual memory, each program gets it's own slice of memory with it's own address 0x0 and it's own address 0x7fffffffe1cc . 使用虚拟内存,每个程序都使用自己的地址0x0和自己的地址0x7fffffffe1cc获取自己的内存片。

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

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