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
| Feature | Stack Memory | Heap Memory |
|---|---|---|
| Creation | Automatically created | Automatically available but requires manual allocation |
| Deallocation | Automatic (when function exits) | Manual (using free() or delete) |
| Speed | Faster | Slower |
| Size | Limited | Large (depends on system) |
| Lifetime | Exists only during function execution | Persists until manually freed |
| Usage | Local variables, function calls | Dynamically 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