We are going to explain what a memory leak is and then provide an example in C++.
A memory leak occurs when a program allocates memory (usually on the heap) but fails to release it back to the system (or to the memory manager) when it is no longer needed.
Over time, this can lead to a program consuming more and more memory, potentially causing performance degradation or even crashing due to running out of memory.
In C++, memory is typically managed manually using new and delete. If you allocate with new and then lose the pointer to that memory (without deleting it), then that memory is leaked.
Example: We will create a simple function that allocates memory but does not free it under certain conditions.
Let's write a function that, given a condition, either leaks memory or not.
We'll also show a more subtle example with a pointer that gets reassigned without deleting the old memory.
However, note that the question asks for an example of how a memory leak can occur. We'll provide two examples:
Example 1: Straightforward leak by forgetting to delete.
Example 2: Leak by reassigning a pointer without deleting the old memory.
But note: the second example is also a form of forgetting to delete, but it's a common mistake when the pointer is overwritten.
We'll write code that demonstrates both.
However, note that the question asks for "an example", so we can choose one. But let's show both for clarity.
But to keep it concise, we can show one and then mention the other.
Let's write a program that has a memory leak in a function and then show how it happens.
A memory leak occurs when a program dynamically allocates memory (e.g., on the heap) but fails to release it when it’s no longer needed. Over time, this unreleased memory accumulates, reducing available memory and potentially causing performance degradation or crashes—even if the operating system reclaims memory when the program exits, leaks are harmful in long-running applications like servers or embedded systems.
Example in C++: Forgetting to delete
#include <iostream>
void leakMemory() {
int* ptr = new int(42); // Allocate memory on the heap
// ... use ptr ...
// Forgot to call: delete ptr;
// ptr goes out of scope, but the heap memory remains allocated.
}
int main() {
while (true) {
leakMemory(); // Each call leaks 4 bytes (assuming sizeof(int)=4)
}
return 0;
}
Why this leaks:
new int(42) allocates memory and returns a pointer ptr.
- The function ends without
delete ptr, so the address is lost but memory stays reserved.
- Repeating in a loop exhausts memory.
Common Causes & Prevention
-
Mismatched new/delete:
- Use
delete[] for arrays (new[]), not delete.
- Pair
new with delete, new[] with delete[].
-
Exception Safety:
void risky() {
int* p = new int(100);
throw std::runtime_error("Oops"); // delete never reached
}
Fix: Use smart pointers (std::unique_ptr, std::shared_ptr) or RAII:
#include <memory>
void safe() {
auto p = std::make_unique<int>(100); // Automatically deleted
}
-
Losing Pointer Values:
int* p = new int(10);
p = new int(20); // Original memory leaked (no delete)
Fix: Delete before reassignment or use smart pointers.
-
Circular References (with shared_ptr):
struct Node {
std::shared_ptr<Node> next;
};
// Two nodes pointing to each other leak memory.
Fix: Use std::weak_ptr for back-references.
Best Practices in Modern C++
- Avoid raw
new/delete: Use containers (std::vector) and smart pointers.
- RAII (Resource Acquisition Is Initialization): Tie memory to object lifetimes.
- Static Analysis Tools: Use Clang’s
AddressSanitizer, Valgrind, or Visual Studio diagnostics to detect leaks.
- C++ Core Guidelines: Prefer
std::unique_ptr for exclusive ownership, std::shared_ptr for shared ownership.
💡 Key Insight: Memory leaks are ownership bugs—tracking who should delete memory is hard without automated tools. Smart pointers shift this burden to the compiler.