Heap memory

From Computer Science Wiki

Heap memory is a region of computer memory used for dynamic allocation of objects at runtime. It is a dynamic area of memory where blocks of memory are allocated and deallocated dynamically as needed, in contrast to the stack memory, where memory is allocated and deallocated in a last-in-first-out (LIFO) manner. Objects stored in the heap have a longer lifetime than objects stored in the stack, as heap-allocated objects persist until they are explicitly deallocated or until the program ends.


Stack and heap are two main memory regions used in a computer program to store data.

Stack memory is used to store data that has a short lifespan and is typically reserved for storing function call frames, function parameters and local variables. Stack memory is accessed in a Last In First Out (LIFO) manner and its size is limited, so it's suitable for storing small amounts of data. When a function call is made, a new stack frame is created and pushed onto the top of the stack, and when the function returns, the stack frame is popped off.

Heap memory, on the other hand, is used for dynamic memory allocation and is typically larger in size compared to stack memory. It is used to store objects and data structures with a longer lifespan. The heap memory is not managed automatically like stack memory, so the programmer is responsible for managing the memory allocation and deallocation using functions such as malloc() and free(). The heap is shared by all functions and has a slower access time compared to the stack.

In summary, stack memory is fast, but limited, and is used for short-term storage, while heap memory is slower, but larger, and is used for long-term storage.