๐
Date: Feb 5, 2026
๐ฅ Topic: Stack vs Heap, new/delete, Memory Leaks
๐ Static vs Dynamic Allocation
Until now, I used int arr[5];. This is Static Allocation (Stack Memory).
Problem: Size is fixed. If I need more space later, I can't get it.
Solution: Dynamic Allocation (Heap Memory). We can ask for memory during runtime using the new keyword.
๐งน The 'new' and 'delete' Keywords
int *arr = new int[5]; // Allocates array on Heap
arr[0] = 10;
// IMPORTANT: We must manually free this memory
delete[] arr;
⚠️ Memory Leak (The Silent Killer)
If I create memory using new but forget to delete it, that space stays occupied forever (until the program ends).
This is called a Memory Leak. In long-running servers, this crashes the system!
๐ญ Thoughts
Manual memory management is risky. That's why C++ introduced Vectors (coming tomorrow) to handle this automatically.
No comments:
Post a Comment