Memory management is a core concept in C++ programming. It refers to how a program allocates, uses, and releases memory during execution. Proper memory management ensures that programs run efficiently, safely, and without memory leaks.
1️⃣ What is Memory Management?
Memory management is the process of:
- Allocating memory
- Using memory
- Releasing memory when no longer needed
Example:
int x = 10;
Here memory is allocated to store the integer value 10.
2️⃣ Memory Layout of a C++ Program
When a C++ program runs, memory is divided into several regions.
+-------------------+
| Stack |
| (local variables) |
+-------------------+
| Heap |
| (dynamic memory) |
+-------------------+
| Data Segment |
| (global/static) |
+-------------------+
| Code Segment |
| (program code) |
+-------------------+
3️⃣ Code Segment
The code segment stores the compiled program instructions.
Example:
void hello()
{
cout << "Hello";
}
The machine code for hello() is stored here.
Characteristics:
- Read-only
- Shared between processes
- Contains program instructions
4️⃣ Data Segment
Stores global and static variables.
Example:
int globalVar = 10;
static int count = 0;
Types:
| Type | Description |
|---|---|
| Initialized Data | Variables with initial values |
| Uninitialized Data (BSS) | Variables initialized to zero |
Example:
int x; // BSS
int y = 5; // initialized data
5️⃣ Stack Memory
Stack memory stores:
- Local variables
- Function parameters
- Function call information
Example:
void func()
{
int x = 5;
}
Memory is automatically allocated and freed when the function exits.
Characteristics:
| Feature | Description |
|---|---|
| Fast allocation | Very fast |
| Limited size | Usually a few MB |
| Automatic management | Compiler manages it |
Example:
int main()
{
int a = 10;
int b = 20;
}
a and b are stored on the stack.
6️⃣ Heap Memory
Heap memory is used for dynamic memory allocation.
Allocated during runtime using:
new
delete
malloc
free
Example:
int* p = new int;
This allocates memory on the heap.
Assign value:
*p = 10;
Free memory:
delete p;
7️⃣ Dynamic Memory Allocation
Dynamic allocation means memory is allocated during runtime.
Example:
int* arr = new int[10];
This allocates memory for 10 integers.
Free memory:
delete[] arr;
8️⃣ new vs malloc
| Feature | new | malloc |
|---|---|---|
| Language | C++ | C |
| Type safe | Yes | No |
| Constructor | Calls constructor | No constructor |
| Syntax | new int | malloc(sizeof(int)) |
Example:
C++ style:
int* p = new int;
C style:
int* p = (int*) malloc(sizeof(int));
9️⃣ Memory Leak
A memory leak happens when memory is allocated but never released.
Example:
int* p = new int;
If delete p; is not called, memory stays allocated.
Problem:
- Memory usage increases
- Program becomes slow
- System crashes
Example fix:
delete p;
🔟 Dangling Pointer
A dangling pointer points to memory that has already been freed.
Example:
int* p = new int;delete p;*p = 10; // ERROR
After deletion, pointer still exists but memory is invalid.
Fix:
delete p;
p = nullptr;
1️⃣1️⃣ Smart Pointers (Modern C++)
Modern C++ uses smart pointers to manage memory automatically.
Types:
| Smart Pointer | Purpose |
|---|---|
| unique_ptr | Single ownership |
| shared_ptr | Shared ownership |
| weak_ptr | Non-owning reference |
Example:
#include <memory>std::unique_ptr<int> p(new int(10));
Memory is automatically freed.
Example:
{
std::unique_ptr<int> p(new int(10));
}
When the block ends, memory is automatically deleted.
1️⃣2️⃣ Stack vs Heap
| Feature | Stack | Heap |
|---|---|---|
| Allocation | Automatic | Manual |
| Speed | Fast | Slower |
| Size | Limited | Large |
| Lifetime | Function scope | Until deleted |
Example:
Stack:
int x = 5;
Heap:
int* p = new int;
1️⃣3️⃣ RAII (Resource Acquisition Is Initialization)
Important C++ concept.
Resources are managed by objects.
Example:
class File
{
public:
File()
{
cout << "Open file\n";
} ~File()
{
cout << "Close file\n";
}
};
Usage:
File f;
When object goes out of scope → destructor runs → resource released.
Used for:
- files
- memory
- mutex locks
- sockets
1️⃣4️⃣ Memory Fragmentation
Fragmentation occurs when memory becomes broken into small pieces.
Example:
[ free ][ used ][ free ][ used ][ free ]
Problem:
Large allocation becomes impossible even if total memory is available.
Heap managers handle fragmentation.
1️⃣5️⃣ Best Practices for Memory Management
Good practices:
✔ Prefer stack allocation
✔ Use smart pointers
✔ Avoid raw pointers
✔ Always free memory
✔ Initialize pointers with nullptr
Example:
int* p = nullptr;
⭐ Example Full Program
#include <iostream>
using namespace std;int main()
{
int* p = new int; *p = 25; cout << *p << endl; delete p; p = nullptr; return 0;
}
Output:
25
⭐ Summary
Memory in C++ is managed using:
| Memory Area | Purpose |
|---|---|
| Code segment | Program instructions |
| Data segment | Global/static variables |
| Stack | Local variables |
| Heap | Dynamic memory |
Key concepts:
new
delete
stack memory
heap memory
memory leaks
smart pointers
RAII