我现在正在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
对我来说很有意义。
所以,问题是,
提前致谢。
答案 0 :(得分:0)
您的程序在称为操作系统的环境中运行。因此,您可能会有更多代码在运作。
1)Stack&amp;堆
第一个线程的堆栈地址由操作系统定义。您可以在PE32 exe文件头中设置一些请求某些特定值的值。但这在Linux上至少是不同的。 C运行时库向操作系统请求一些内存。 IIRC与functionluerk。操作系统可以根据需要提供内存。请记住,尽管您有一个线性地址空间,但您没有连续的内存布局。它更让人想起瑞士奶酪。
2)局部变量的地址
这是一种未指定的行为。编译器可以自由地为内部变量分配内存中的顺序。有时我看到订单是按字母顺序排列的(只是尝试重命名),或者它随着optmization的级别而变化。接受它。