Topic 43 of 83
Dynamic Memory
Overview
Local variables are stored on the Stack (small, automatic). Dynamic memory is allocated on the Heap (huge, manual) using `new` and must be manually freed using `delete`.
Syntax
cpp
// Allocate an integer on the Heap
int* ptr = new int;
*ptr = 42;
// Allocate and initialize
int* ptr2 = new int(100);
// FREE the memory to prevent leaks
delete ptr;
delete ptr2;
// Good practice: nullify the pointer
ptr = nullptr;Common Pitfalls
- Forgetting to `delete`, leading to memory leaks that eventually crash the program (OOM - Out of Memory).
Interview Tips
- A Memory Leak occurs when you lose all pointers to dynamically allocated memory without calling `delete`.
- A Dangling Pointer occurs when you call `delete ptr`, but you try to use `ptr` again later. Always set `ptr = nullptr` after deleting.
Real-World Example
Allocating a large object on the heap to save stack space.
example
cpp
#include <iostream>
using namespace std;
struct MassiveData {
long long data[10000];
};
int main() {
// Allocating on heap prevents Stack Overflow
MassiveData* md = new MassiveData();
md->data[0] = 500;
cout << "Value: " << md->data[0] << endl;
delete md; // Crucial!
return 0;
}