Please read the following C++ code and the results. According to some wiki pages, static, automatic and dynamically-allocated variables are allocated in different address spaces, namely, data segment, stack and heap. However, it seems to me that the address of static and dynamic variables are at about the same place. Why is that so? How do I know the static variable is really in data segment, not in heap?
A more broad question is whether it is possible in C++ to know the range (or available size) of each address space?
Another question I have is why the address of volatile variable is 1?
#include <iostream>
using namespace std;
static int i;
int main() {
cout << sizeof(int*) << endl;
int j;
int* k = new int[10];
volatile int l;
cout << &i << endl;
cout << &j << endl;
cout << k << endl;
cout << &l << endl;
delete[] k;
}
Results:
8
0x1000010e4
0x7fff5fbff66c
0x100100080
1
Only the OS can tell you which sections are in which parts of the address space. If you’re using Linux, From within the program, output the contents of
/proc/self/maps:I’ve added
at the end of your program, and it prints:
As for printing the address of a
volatile int, there is no standardoperator<<that takes a pointer-to-volatile-T, but there is one that takesbool, and any pointer can be implicitly converted tovoid*, which then can be converted tobool. To print the address you want, change that line to