What “Dynamic Memory” Really Means
Memory in a program is of two main types:
• Static / Automatic memory → decided at compile time
• Dynamic memory → decided at runtime
Dynamic memory means:
memory is requested while the program is running, not before.
Problem with Normal Variables (Why Dynamic Memory is Needed)
When you write:
This memory:
• is fixed
• size cannot change
• destroyed automatically when scope ends
Example:
When func() ends:
• memory of x is destroyed
• you cannot access it anymore
But sometimes:
• size is unknown
• data must survive longer
• memory must be controlled manually
This is where dynamic memory is needed.
Where Dynamic Memory Lives (VERY IMPORTANT)
Dynamic memory is allocated in a special memory area called the:
Heap
Memory areas:
| Area | Purpose |
|---|---|
| Stack | Local variables, automatic |
| Heap | Dynamic memory (manual) |
• Stack → fast, automatic
• Heap → flexible, manual
new Operator
What new Does Internally
When you write:
The system does four things:
Finds free memory in heap
Allocates enough bytes for
intReturns the address of that memory
Stores the address in pointer
p
Memory view (example):
Assigning Value to Dynamic Memory
Or directly:
Now heap memory contains:
Why Pointer is REQUIRED
Dynamic memory:
• has no variable name
• only accessible via pointer
This is illegal:
Correct:
Example 1: Basic Dynamic Variable
Explanation:
• memory allocated at runtime
• accessed using pointer
• manually deleted
Dynamic Memory for Arrays (VERY IMPORTANT)
Static Array Problem
Size:
• fixed
• must be known at compile time
Dynamic Array Solution
Now:
• memory allocated in heap
• size decided at runtime
Memory layout:
Example 2: Dynamic Array Input
Important:
• delete[] is REQUIRED for arrays
delete Operator
What delete Really Does
Steps:
Frees heap memory
Memory becomes available again
Pointer still holds old address (DANGEROUS)
That pointer becomes:
Dangling pointer
Why nullptr is Important
After delete:
This ensures:
• pointer does not point to garbage
• safer memory handling
Difference Between delete and delete[]
| Allocation | Deallocation |
|---|---|
new int | delete p |
new int[n] | delete[] p |
Wrong usage causes:
• memory leaks
• undefined behavior
Memory Leak (VERY IMPORTANT)
What is Memory Leak?
Memory leak happens when:
• memory is allocated
• but never deleted
Example:
Result:
• memory stays occupied
• program wastes RAM
In long-running programs:
• crash
• slow performance
Correct Pattern (Best Practice)
Example 3: Dynamic Memory in Function
Why this works:
• memory is in heap
• survives function end
• controlled by programmer
Common Errors (VERY IMPORTANT)
1. Using memory after delete
2. Double delete
3. Forgetting delete
Dynamic Memory vs Stack Memory
| Feature | Stack | Heap |
|---|---|---|
| Allocation | Automatic | Manual |
| Speed | Fast | Slower |
| Size | Limited | Large |
| Lifetime | Scope-based | Programmer-controlled |