堆栈和堆地址区域在Windows和linux中是不同的

Stack and Heap address region is differs in Windows and linux

本文关键字:linux Windows 是不同 地址 区域 堆栈      更新时间:2023-10-16

我现在正在测试c++中堆和堆栈的地址区域

我的代码是

#include <iostream>
using namespace std;
int g;
int uninitialized_g;
class Heap{
int a;
int b;
};
int main() {
int stack_variable = 3;
int stack_variable_1 = 3;
g = 3;
Heap * heap_class = new Heap;
Heap * heap_class_1 = new Heap;
cout << "Static initialized g's addr = " << &g << endl;
cout << "Static un-initialized g's addr = " << &uninitialized_g << endl;
cout << "Stack stack_variable's addr = " << &stack_variable << endl;
cout << "Stack stack_variable1's addr = " << &stack_variable_1 << endl;
cout << "Heap heap_class's addr = " << heap_class << endl;
cout << "Heap heap_class1's addr = " << heap_class_1 << endl;
delete heap_class;
delete heap_class_1;
return 0;
}

,在带有MinGW的windows eclipse中,结果是

Static initialized g's addr = 0x407020
Static un-initialized g's addr = 0x407024
Stack stack_variable's addr = 0x22fed4
Stack stack_variable1's addr = 0x22fed0
Heap heap_class's addr = 0x3214b0
Heap heap_class1's addr = 0x3214c0

,在Linux下使用g++的结果是

Static initialized g's addr = 0x601180
Static un-initialized g's addr = 0x601184
Stack stack_variable's addr = 0x7ffff5c8c2c8
Stack stack_variable1's addr = 0x7ffff5c8c2cc
Heap heap_class's addr = 0x1c7c010
Heap heap_class1's addr = 0x1c7c030

对我来说是有意义的。

问题是,

  1. 在windows的结果,为什么堆内存地址分配有时高于堆栈?
  2. 在linux中,堆寻址是有意义的。但是为什么堆栈地址越来越高呢?

您的程序在称为操作系统的环境中运行。因此,可能会有更多的代码在运行。

1) Stack &堆

第一个线程的堆栈地址由操作系统定义。您可能会在PE32 exe文件头中设置一些值,以请求某些特定值。但这至少在Linux上有所不同。C运行时库向操作系统请求一些内存。IIRC函数s_brk。操作系统可以随心所欲地提供内存。请记住,尽管您有一个线性地址空间,但您没有一个连续的内存布局。它更像瑞士奶酪。

2)局部变量的地址

这是一个未指定的行为。编译器可以自由地在内存中为局部变量分配顺序。有时我看到顺序是按字母顺序排列的(只需尝试重命名),或者它会随着优化级别的变化而变化。