What is real difference between stack memory and heap memory?

I have heard of this stack and heap during my computer classes during the study of recursive functions and all.I have just reached my 2nd year…But i would like to know what is this stack and heap.Can any one please help me out in simple words? We can imagine it in our mind.But the memory is not like that in originality right?

2 Likes

The differences between the stack and the heap can be confusing for many people.

  1. Both stack and heap are stored in memory(RAM). In multithread each thread have it’s own stack whereas different thread share heap.

  2. One of the big difference between stack and heap is size , stack size is fixed i.e. we get stackoverflow error , whereas heap size is operated by OS and can be change according to the needs.

  3. Stack is much faster than a heap . Since in stack memory allocation is easy and moving the stack pointer up.

  4. For programming purpose , it’s better to use stack rather than heap bcz it’s easier to allocate memory on stack.

If size of data is small use stack if not use heap .

There are many links on net where can get more information about heap and stack

6 Likes

@Sp1rs:So stack is more faster?

@bipin2 Yes and also easier to implement .

Stack is used for static memory allocation and Heap for dynamic memory allocation, both stored in the computer’s RAM .

Variables allocated on the stack are stored directly to the memory and access to this memory is very fast, and it’s allocation is dealt with when the program is compiled. When a function or a method calls another function which in turns calls another function etc., the execution of all those functions remains suspended until the very last function returns its value. The stack is always reserved in a LIFO order, the most recently reserved block is always the next block to be freed. This makes it really simple to keep track of the stack, freeing a block from the stack is nothing more than adjusting one pointer.

Variables allocated on the heap have their memory allocated at run time and accessing this memory is a bit slower, but the heap size is only limited by the size of virtual memory . Element of the heap have no dependencies with each other and can always be accessed randomly at any time. You can allocate a block at any time and free it at any time. This makes it much more complex to keep track of which parts of the heap are allocated or free at any given time.

More about…Stack and Heap

Mark