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 understand the memory allocation pattern in the following snippet. Can anyone help me to understand this.
If there any thing more apart from the variable types mentioned in the example to help understand the concept better please alter the example.
class FooBar
{
int n; //Stored in stack?
public:
int pubVar; //stored in stack?
void foo(int param) //param stored in stack
{
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?
string str = "mystring"; //stored in stack?
..
if(CONDITION)
{
static int nSIf; //stored in static area of memory
int loopvar; //stored in stack
..
}
}
}
int main(int)
{
Foobar bar; //bar stored in stack? or a part of it?
Foobar *pBar; //pBar is stored in stack
pBar = new Foobar(); //the object is created in heap? What part of the object is stored on heap
}
EDIT:
What confuses me is, if pBar = new Foobar(); stores the object on the heap, how come int nLoc; and int pubVar;, that are components of the object stored on stack? Sounds contradictory to me. Shouldn’t the lifetime of pubvar and pBar be the same?
“Heap” and “stack” are outmoded, inaccurate and confusing terms relating to storage duration.
Objects with “automatic storage duration” are what silly people call “stack objects”. They’re the ones that you will define inside a function as “local variables”. They go out of scope when their enclosing block ends.
Objects with “dynamic storage duration” are those that you create on the free store with the aid of the keyword
new(or, if you’re silly,malloc), and then destroy whenever you like with the keyworddelete(or, if you’re silly,free).There are also objects with “static storage duration” that are subject to all sorts of bizarre rules of initialisation order and things. We tend not to use them in idiomatic C++ as much as we can help it.
As for the specific variables in your code example, your comments are all accurate, despite the failure in terminology.
Addendum:
The terms “heap” and “stack” are outdated, relating to back when the most popular runtime libraries used these data structures to store objects which were dynamically- and automatically-allocated, respectively (statically-allocated objects fit into neither category, incidentally).
These days that is not always true, and it’s certainly not mandated by the C++ standard, which does not care where things are stored. It only cares about how they are created and destroyed, and about how long they live.