Stack & Heap Memory Explanation

Hi,

I'm at a total loss as to what stack and heap memory are and keep getting confused about them. I was wondering if any experts know of any good resources, which they think explain the topic tastefully???


Thanks

bowemcAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

avinthmCommented:
The memory allocated dynamically , all goes into heap.
All static allocation goes into stack, like declaration of arrays.

http://www.experts-exchange.com/Programming/Q_21732634.html
http://www.codersource.net/c++_dynamic_memory_allocation.aspx
http://cplus.about.com/od/beginnerctutorial/l/aa072502b.htm
DineshJolaniaCommented:
rajeev_devinCommented:
>> All static allocation goes into stack, like declaration of arrays.
Wrong. local variable goes into stack.
static allocation goes into data area of the program.
Angular Fundamentals

Learn the fundamentals of Angular 2, a JavaScript framework for developing dynamic single page applications.

DrAskeCommented:
This is a good explanation from neitod
{{{{{{
First of all, the C++ language standard makes no mention of stacks and heaps (in this context at least).  The language prescribes only how a program is to behave, not how that behavior is to be achieved.  So it is possible that a C++ program might not make use of a stack or heap.  however, that said, most C++ complilers do create C++ programs that use both

The fundamental difference between the two is an issue of lifetime or duration.  

Some data in a C++ program has a well--defined lifetime, that is, the data's declaration makes clear when the data is to be created and destroyed.  In addition, much of this data, like non-static local variables, has a lifetime that is of a "hierachical" nature and is related to program scope  That is when object A is created and then object B is created, then object B must be destroyed before object A.  This sort of behavior is seen both between non-static local variables within a function a well as between non-static local variables in one function and a 2nd function called by the first function.  

Data like this is often best stored on a stack.  A stack is a LIFO (last in first out) storage mechanism.  This means that an item stored on the stack will be removed after any newer items are removed and before any older items are removed.  This is the exact order in which nonstatic local variables need to be created and destroyed.

A heap is usually used for data that has an indeterminate lifetime, like data allocated with operator new or malloc().  This data can be destroyed in an order that does not depend on the order in which other data is created or destroyed.  it can be created in one procedure and then destroyed much ;later in a seperate procedure.  It might be created in one procedure and then destroyed in a procedure called by the one that created.it.  This sort of lifetime is very different than the lifetime associated with stack data.
 
 
}}}}}}
and this is from *mrwad99*
{{{{{{
The stack is called so because it is analogous to a stack of objects - the current object is pointed to by a register in the CPU called the stack pointer.  By manipulating this pointer you can access different memory locations: consequently operating on the stack pointer is a very fast and efficient operation.  

Conversely, the heap is an area of memory that is not pointed to by the stack pointer,  thus is slower to access.

Creating an object on the stack will mean that the memory allocated to it will automatically be freed by the compiler, either by calling the destructor of the object implicitly (if it is a new type you have created) or by freeing the memory given to any primative types, such as int or long, when the object in question *goes out of scope*.

Creating an object on the heap is as simple as stating

int a = 10;

This sets aside the memory required for an int (32 bit int is 4 bytes of memory), and assigns 10 to that memory location.

MyClass a;

This sets aside the memory required to hold an instance of a custom class MyClass.  The total memory required for this will be the sum of all the constituent variables inside the class, so if it held four ints, the total memory put aside would be (4*4) = 16 bytes.

When either of these objects go out of scope, the concerned memory will be put back onto the stack for later use.  Since the stack is of limited size, this is very important.  Of course, you can delete the class instance before it goes out of scope, like this:

a.~MyClass();

By 'out of scope' I mean either the end of your main method, or the end of the function, whichever the variable/object is created in.

Creating an object on the heap however is different.  The memory allocated will not be deleted automatically unless you explicitly call the destuctor.

To create an object on the heap you would use the 'new' keyword.

For example,

MyClass* a = new MyClass();

Now this allocates 16 bytes on the heap.  This memory will not be deleted (and will result in 16 bytes being lost in your program, i.e. a memory leak) unless you call

delete a;

I think this answers the latter part of your question as to when objects are created on the heap or not.  Basically anything involving a 'new' call will be created on the heap, otherwise it will be on the stack.

}}}}}}}}}}}}}}}}}}


regards;

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Prashant SabnekarAVPCommented:
Dear bowemc,
dont get confused, memory management is a simple thing.
When we declare variables in our programs, we actually allocate some space with a name which is our variable name (identifier). Now this space can be allocated either statically or dynamically.
By statically I mean allocating memory on a stack (exactly speaking a program stack).
By dynamically I mean allocating memory on heap (heap is not the area of the program).
Now when the program terminates, the memory allocated by the compiler on stack will be cleaned up automatically, but the memory created on heap will not be cleaned up automatically, It has to be cleaned explicitly ( delete ), otherwise a program is said to have a 'memory leak'.
Static Allocation
Eg: int n;
char name[25];
No problem
Dynamic allocation
Eg:
int* n;
n=new int;
char* name;
name=new char[25];
needs this, in distructor
delete n;
delete [] name; //[] because this is an array

I hope you understand, I advise to do some programs and test it by some memory tools (memprof etc) to find leaks, If you want any extended help, I am allways there.

All the best

Prashant Sabnekar
Infinity08Commented:
>> static allocation goes into data area of the program.
A bit more on this : the compiler decides where to put the static data. It might put it in a separate block of data memory. It might even put it between the heap and stack. Some put it in the code area (which i don't consider to be very secure).

In any case, it's a fixed size block of memory that can't be used for anything else than the static data it was destined for.
Infinity08Commented:
>> Now this space can be allocated either statically or dynamically.
Actually, there's 3 storage types : statically (in static memory), dynamically (on the heap), and automatically (on the stack).

>> By statically I mean allocating memory on a stack (exactly speaking a program stack).
static data is generally NOT put on the stack, as there's no point in that ... the stack follows the call flow of the program, while the static data remains for the duration of the program. Some compilers might put it at the bottom of the stack, but as i said : conceptually, that's not logical.

>> By dynamically I mean allocating memory on heap (heap is not the area of the program).
What do you mean by "not the area of the program" ? The heap for a program is a part of the memory allocated to the program by the OS.

>> Now when the program terminates, the memory allocated by the compiler on stack will be cleaned up automatically, but the memory created on heap will not be cleaned up automatically,
When the program terminates, all memory (including the heap) is returned to the OS. This to ensure that problems in the code (like memory leaks) don't affect the operation of the OS or the other software running on the system.

>> It has to be cleaned explicitly ( delete ), otherwise a program is said to have a 'memory leak'.
If you don't free a block of allocated memory, and there's no reference (pointer) to that block any more, then that's called a memory leak, because that block of memory can't be used by the program any more, and is thus effectively memory that "leaked" away.
As i said however : when the program terminates, all memory leaks are effectively undone !
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C++

From novice to tech pro — start learning today.