Question

I'm now testing the address area of heap and stack in C++

my code is

#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;
}

and in windows eclipse with MinGW, the result is

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

and in linux with g++ result is

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

which make sense to me.

So, the questions are,

  1. In windows result, why is heap memory address allocated sometimes higher than stack?
  2. In linux, heap addressing makes sense. But why stack address grows higher?

Thanks in advance.

Was it helpful?

Solution

Your program runs in an environment called operating system. So there is more code in action as you probably expected.

1) Stack & Heap

The stack address of the first thread is defined by the operating system. You might set some values in the PE32 exe file header that request some specific value. But this is at least different on Linux. The C runtime library requests the operating system for some memory. IIRC with the function s_brk. The operating system can provide memory as it likes. Keep in mind that despite you have a linear address space you don't have a contiguous memory layout. It more reminds to a swiss cheese.

2) Addresses of local variables

This is a not specified behavior. It is free to the compiler to assignd the order in memory for the local variables. Sometimes I have seen that the order is alphabetical (just try a rename) or that it changes with the level of optmization. Just accept it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top