I am confused about the memory allocation in C++ in terms of the memory areas such as Const data area, Stack, Heap, Freestore, Heap and Global/Static area. I would like to u
I've updated your annotations with what I believe is more correct. Note that Tomalak is correct that 'stack' and 'heap' are not specified by the standard, and mechanisms other than a stack might be used to pass parameters to store automatic variables.
However, I still use those terms because they are actually used quite often in compiler implementations, the terms are more or less well-understood (or easy to understand), and I think they still pragmatically illustrate what you're interested in knowing.
class Foobar
{
int n; //Stored wherever the current object is stored
// (might be static memory, stack or heap depending
// on how the object is allocated)
public:
int pubVar; //Stored wherever the current object is stored
// (might be static memory, stack or heap depending
// on how the object is allocated)
void foo(int param) //param stored in stack or register
{
int *pp = new int; //int is allocated on heap.
n = param;
static int nStat; //Stored in static area of memory
int nLoc; //stored in stack or register
string str = "mystring"; // `str` is stored in stack, however
// the string object may also use heap
// to manage its data
..
if(CONDITION)
{
static int nSIf; //stored in static area of memory
int loopvar; //stored in stack or register
..
}
}
}
int main(int)
{
Foobar bar; //bar stored in stack
Foobar *pBar; //pBar is stored in stack
pBar = new Foobar(); //the object is created in heap.
// The non-static data members are stored in that
// memory block.
}