Link to home
Start Free TrialLog in
Avatar of migue
migue

asked on

What happens to memory ??

If I have  a class that is instantiated locally, and now the object's ctor allocates memory for its purpose. Does the object itself lives in the heap and so is its allocated data members ? or The object is allocated to the function's stack and the objects allocated data members live on the heap ?

I would like to know the difference scenarios of what data goes where.
Avatar of kellyjj
kellyjj

I believe that the object should not exist outside the scope of where you init it.  However, if the obj is not needed globally, then you should clean it up before leaving.
ASKER CERTIFIED SOLUTION
Avatar of gaohong
gaohong

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
If the object is instanciated locally, that is, it is not created using the new operator, then the object is allocated on the stack not on the heap.  However if the object allocates memory with new inside its ctor (or other procedures), that memory is on the heap.  However the object itself remains on the stack.  It just uses a pointer to memory in the heap.
There are 3 locations for data.  

Global data that is data that is not defined inside (local to)  a procedure and is not allocated with new, is stored in the program's data areas.  Often room is allocated for this data alongside the program's code.

Local data is data that is declared inside a procedure without using the new operator.  It is allcoated on the program's stack.

Dynamic data is allocated using the new operator (or C's malloc).  It is allocated on the program's heap (or heaps).

let's say you make a character array:

void f() {
   char stackBuffer[80];
   char* heapBuffer = new char[80];
}

stackBuffer array is stored on the stack, is destroyed automatically as you leave the function

the heapBuffer *pointer* is on the stack, is destroyed automatically as you leave the function

the *object* (the array of chars) is created on the heap and will stay there until you use delete to deallocate it

so if you don't delete the object that heapBuffer pointer is pointing to, you will lose the pointer and the access when you leave the function, but the object will still reside in memory, inaccessible (unless you use an object in a larger scope, like a class data member for instance).