Post

Stack/Heap Memory

Stack/Heap Memory

This post was migrated from Tistory. You can find the original here.

Stack Memory

This is the area where local variables and parameters related to function calls are stored.

When a function is called, the return address to jump back to once the call finishes, the function’s parameters, and the local variables declared inside the function are all stored on the stack, and they are destroyed once the call completes.

Everything about stack memory is determined at compile time. In other words, the developer doesn’t write any code to manage it.

The stack runs independently per thread.

The stack is faster to allocate/deallocate than the heap.

why => Since the stack is pre-reserved memory, no separate memory allocation is needed, and used memory isn’t explicitly returned (i.e., there’s no deletion step) — the stack space is simply shrunk by decrementing the stack pointer. The leftover data that remains after decrementing the stack pointer is later just overwritten when the stack pointer increases again and reuses that space.

The data stored on the stack is called a stack frame, and it operates on a FILO (first-in-last-out) basis.

A stack overflow occurs when the stack memory space is exceeded.

Heap Memory

This is a dynamic memory area determined at runtime. In other words, the developer writes code to control it directly.

It’s managed through the malloc, calloc, realloc, and free functions, whose size can be adjusted using the brk and sbrk system calls.

The heap can be referenced by every running thread, which means it is not thread-safe.

If a developer doesn’t manage heap memory properly, a memory leak can occur.

The heap is slower to allocate/deallocate than the stack.

why => It’s the opposite of the reason above. The memory has to be calculated and evaluated before it can be allocated/deallocated.

The main issue with the heap is memory fragmentation caused by dynamic memory management.

Memory fragmentation - a state where, even though the remaining space would be enough if combined, it’s split into small chunks so that allocation becomes impossible.

References

https://blog.naver.com/PostView.nhn?blogId=techref&logNo=222274484731

https://jiwondev.tistory.com/86

http://www.tcpschool.com/c/c_memory_structure

This post is licensed under CC BY-NC 4.0 by the author.