variables addresses

Please look at this code:

int main()
{

int a=5;
int b;
int *c=new int(5);

cout<<&a<<endl; //0012FED4
cout<<&b<<endl; //0012FEC8
cout<<&c<<endl; //0012FEBC

return 0;
}

As you can see there is 12 bytes space between every address.

Now look at this:


int a=5;
int b=8;
int c;
int *d=new int(5);

int main()
{
cout<<&a<<endl; //00456014
cout<<&b<<endl; //00456018
cout<<&c<<endl; //004576A0
cout<<&d<<endl; //004576A4

return 0;
}

Between Variable (a) and (b) is 4 bytes space but for (c) its different. There is approximately 6000 bytes space. What’s the point of this?

I’ve learnt that initialized variable is stored in .data section, uninitialized variables in .bss and pointers in heap. But here I am really confused. Why addresses in code one is contiguous with 12 bytes spaces. Why 12? If integer is 4 bytes! What is this extra 8 bytes?
And why uninitialized variable is close to a pointer variable that is supposed to be in heap section.
Why base address for variables inside main function is 0012FED4 but for second code its 00456014.

Please someone write me a line about this issue.
Thanks for any advance.

Why 12? If integer is 4 bytes! What is this extra 8 bytes?


If you are building in debug mode, the compiler might be padding with magic numbers to detect stack corruption.

Why base address for variables inside main function is 0012FED4 but for second code its 00456014.


Variables local to a function go on the stack. Other variables don't. Globally defined variables might be put on the heap or in some other area, but they don't appear to be going on the stack like local vars are.

And why uninitialized variable is close to a pointer variable that is supposed to be in heap section.


Beats me.
Last edited on
>Why base address for variables inside main function is 0012FED4 but for second code its 00456014.


Variables local to a function go on the stack. Other variables don't. Globally defined variables might be put on the heap or in some other area, but they don't appear to be going on the stack like local vars are.
Static data (including globals) is allocated in a special memory region separate from the heap and the stack.
Note that both this region and the stack may be placed at different locations each run.

And why uninitialized variable is close to a pointer variable that is supposed to be in heap section.
The pointer itself exists in the static region. The data it points to exists in the heap. Try printing d instead of &d.
Now, there's some subtlety as to why d was put next to c. In fact, d is being treated by the compiler as uninitialized because the value you're trying to initialize it with (a memory address of data in the heap) can't be known at compile time. It puts it in .bss and then initializes it before main() is called.
Last edited on
Topic archived. No new replies allowed.