Skip to main content

Memory Managment

A program stores in hard drive, executes in CPU.

Think of it like a book:

  • Hard Drive = A bookshelf where the book (program) is stored when not in use.
  • RAM = A desk where you place the book while reading it (temporary workspace).
  • CPU = Your brain, which reads and processes the information from the book.

Types

Code Segment

  • Store compiled code.
  • It uses stack and heap memory.

Stack Memory

  • Store global, static variable, function call
  • Automatically managed(created, removed)
  • Size decided at compile time
  • Store data organized way

Heap Memory

  • Memory allocated during program execution
  • Automatically created but manually removed
  • when the programs terminates, OS automatically reclaims all allocated heap
  • Size decided at run time
  • Store data unorganized way
  • Treat like resources
  • Can't directly use, you have to use pointer to use it

Comparison: Stack vs Heap

FeatureStack MemoryHeap Memory
CreationAutomatically createdAutomatically available but requires manual allocation
DeallocationAutomatic (when function exits)Manual (using free() or delete)
SpeedFasterSlower
SizeLimitedLarge (depends on system)
LifetimeExists only during function executionPersists until manually freed
UsageLocal variables, function callsDynamically allocated memory
  • Array created in both heap(int *p=new int(5)) and stack(int arr[]={1,2,3,4,5}).
  • Linkedlist created only in heap.

Allocation

Static Memory Allocation

  • Memory allocated at compile time and doesn't change during program execution, deallocated automatically when program terminates.
  • It is stored in the stack/data segment.
  • Global variable store in data segement and local variable store in stack.

Dynamic Memory Allocation

  • Memory allocated at runtime using pointers.
  • It is store in the heap memory.
  • Explicit deallocation requires.

Example:

int *p;  // store at stack as it is local variable
p=new int(5); // store at heap