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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With