Could you help me understand where variables are stored (stack, heap, static memory).
How can I determine it? I mean not intuitively but I would like to have some sign printed on the screan what is where. Is it possible?
So far I tried to have a look at where the variables are stored by printing their addresses.
But that didn’t give me much. Could you have a look and give me a piece of advice.
If I’ve made a mistake (see my comments to the program), please tell me about that.
#include "stdafx.h"
#include <iostream>
using namespace std;
int * p1 = new int [3]; // Static memory as it is a global array;
namespace P {int * p2 = new int[3];} // Static memory as it is a namespace;
namespace {int * p3 = new int[3];} // Static memory as it is a namespace;
using namespace P;
int _tmain(int argc, _TCHAR* argv[])
{
int * p4 = new int[3]; // Heap as there is a new operator.
static int * p5 = new int [3]; // Static memory as the variable is static.
cout << "p1: "<< p1 << endl;
cout << "p2: "<< p2 << endl;
cout << "p3: "<< p3 << endl;
cout << "p4: "<< p4 << endl;
cout << "p5: "<< p5 << endl;
cout << endl;
cout << "p5 - p4: " << p5 - p4 << endl;
cout << "p4 - p3: " << p5 - p4 << endl;
cout << "p3 - p2: " << p5 - p4 << endl;
cout << "p2 - p1: " << p5 - p4 << endl;
system("pause");
}
Only the pointer is static here. The stuff it points to is on “the heap”, meaning it is dynamically allocated and the caller needs to take care of de-allocating. Where the data actually is is another matter. It depends on the platform, and on what
newis defined to do.Have a look at this GotW. Thanks to @AlokSave for posting it in the comments.