Sitemap
leedohyung28

leedohyung28

Stack, Heap Memory

2 min readAug 13, 2024

--

In Memory, there is Stack and Heap

Press enter or click to view image in full size

*Code : the area where the running program’s code is stored
*Data : the area where the program’s global variables and static variables are stored

Stack Area in Memory

  • Used to Call functions, Store local variables, Manage state when function returns …
  • Memory is automatically managed by Compiler
  • When function is called → ‘Stack frame’ is created
    When function is ended → ‘Stack frame’ is removed
  • LIFO (Last In, First Out) Structure : Data which come last will be out first
    Saving data via PUSH
    Fetching data via POP
  • Allocate in direction of high to low address in memory

Heap Area in Memory

  • Allocate and release non-sequential memory
  • Used when dynamic memory allocation is required
  • Data structures change size during program execution (ex. Array, List …)
  • Programmer explicitly allocates and frees memory
    (Memory allocation : malloc in C, new in C++, …)
    (Memory free : free in C, delete in C++, …)
  • Allocate in direction of low to high address in memory

Stack vs. Heap

Features of Stack

Fast memory access
Managed directly by CPU
Easy to manage memory

Get leedohyung28’s stories in your inbox

Join Medium for free to get updates from this writer.

Too many function calls can cause Stack Overflow
(Stack Overflow : An error which occurs when the limit of stack memory is exceeded (When the stack pointer crosses the boundary of the stack) and no more data can be stored)

Features of Heap

Users can allocate as much memory as they need which make size flexible
Suitable for implementing complex data structures (Linked List, Tree, Graph …)

Slow to access compared to stack
Memory management is complex
If users do not free memory, ‘Memory leak’ occurs
(However, many languages (Java, Python, C# ..) have Garbage Collectors which automatically free memory prevents Memory leak)

Conclusion

Except for C/C++ most languages have Garbage Collector which manages memory in Heap area.
However, Heap is slower and complicated in Stack
but can make memory size flexible and can be used in complicated memory structure.

To know all these knowledge is basic to manage memory and make program more efficient in programming

--

--