top of page

Difference Between Stack and heap Memory


1. Stack Memory:


  • Purpose: Used for static memory allocation and local variables. It also stores function call information, such as return addresses, parameters, and local variables.

  • Memory Allocation and Deallocation: Stack memory is managed automatically by the operating system. Memory is allocated when a function is called and deallocated when the function returns.

  • Size: Typically smaller and limited in size compared to heap memory. The size is determined at the start of the program and can lead to stack overflow if exceeded.

  • Access Speed: Fast access due to its contiguous memory allocation and LIFO (Last In, First Out) structure.

  • Scope: Variables in stack memory have limited scope; they are only accessible within the function that declared them. Each thread has it's own stack memory.

  • Data Lifespan: The lifespan of data in the stack is short, tied to the function call. When a function call ends, its stack frame is destroyed, and the data is lost.

  • When stack memory goes full it throws stackOverFlow error.


2. Heap Memory:

  • Purpose: Used for dynamic memory allocation, which allows allocating memory at runtime. Suitable for storing data whose size is not known at compile time or for objects that need to persist beyond the scope of a function.

  • Memory Allocation and Deallocation: Managed manually by the programmer (in languages like C/C++) or by a garbage collector (in languages like Java). Memory is allocated using functions like malloc in C or the new operator in Java and C++. It must be explicitly deallocated using free in C or delete in C++.

  • In Java garbage collector is used to delete the unreferenced objects from the heap.

  • Size: Generally larger and more flexible than stack memory, allowing for allocation of more significant amounts of memory.

  • Access Speed: Slower access compared to stack memory due to its fragmented nature and the need for pointer dereferencing.

  • Scope: Variables in heap memory can be accessed globally, as long as a reference to them exists. heap memory is shared with all the threads.

  • Data Lifespan: Data can persist beyond the function that created it, lasting until it is explicitly deallocated or the program terminates. This can lead to memory leaks if not managed properly.

  • when heap memory goes full it's throws "java.lang.outOfMemoryError"



ree

 
 
 

Comments


Call 

7869617359

Email 

Follow

  • Facebook
  • Twitter
  • LinkedIn
  • Instagram
Never Miss a Post. Subscribe Now!

Thanks for submitting!

bottom of page