What is Memory?
Every program uses RAM (Random Access Memory) to temporarily store:
- Variables and constants
- Function calls and return addresses
- Objects and data structures
There are two main areas in memory where data is stored:
Type | Location | Managed By | Lifetime |
---|---|---|---|
Stack | System-managed | Compiler | Automatically managed (ends with scope) |
Heap | Programmer-managed | Manual / Smart pointers | Requires manual allocation and deallocation |
Stack vs Heap
Stack Memory:
- Fast and automatically managed
- Stores local variables and function calls
- Memory is freed automatically when scope ends
void foo() {
int x = 10; // Stored on the stack
} // x is destroyed here
Heap Memory:
- Used for dynamic memory allocation
- Slower but more flexible
- Must be explicitly managed (with
new
/delete
)
int* ptr = new int(5); // Allocated on heap
delete ptr; // Must be manually deleted
Why Use Dynamic Memory?
Use Case | Stack | Heap |
---|---|---|
Unknown size at compile-time | ❌ | ✅ |
Long-lived objects | ❌ | ✅ |
Large data structures | ❌ (may cause stack overflow) | ✅ |
For example:
int* arr = new int[n]; // 'n' determined at runtime
Dangers of Manual Memory Management
With Great Power Comes Great Responsibility.
Dynamic memory gives power—but also responsibility. Common issues include:
- Memory leaks: Forgetting to
delete
memory → unused memory stays reserved - Dangling pointers: Accessing memory after it’s been freed
- Double delete: Trying to delete the same memory twice
- Buffer overflows: Writing beyond allocated memory
These issues can lead to crashes, data corruption, and security vulnerabilities.