Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between the address stored and displayed in C and C++?

Tags:

c++

c

In C, if I make a variable and print its address like this:

int a;
int main (void) {
    printf ("%p", &a);
    return 0;
}

The output was: 00AA

The same program in C++ using the line:

cout << &a << endl;

The output was: 0x8f970aa

What is the difference between these two?

I compiled both the programs using Turbo C.

like image 444
Developer101 Avatar asked Mar 27 '15 15:03

Developer101


1 Answers

Unless you are using some special, system-specific linker file, there are no guarantees of which address your variables will end up at in memory. It might even end up in different places from compilation to compilation on the same compiler. And of course different compilers will behave differently. There's no standard stating how they should allocate variables.

This has nothing to do with C versus C++. Both standards state that your variable should be allocated with static storage duration. All static storage duration variables that are not explicitly initialized are guaranteed by the C and C++ standards to get initialized to zero (see for example C11 6.7.9/10).

This means that both standards indirectly guarantee that the variable is allocated in .bss. Exactly where in the .bss is not specified anywhere.

Related question.

like image 123
Lundin Avatar answered Sep 18 '22 13:09

Lundin