Memory Leaks
Concept Definition
A memory leak happens when allocated memory is no longer reachable and cannot be released. In C++, this often comes from new without a matching delete, or from ownership paths that are skipped by early return or exception. The program may keep running, but memory usage grows incorrectly.
A useful analogy is checking out books and losing the receipts. The library knows books are gone, but nobody knows how to return them.
Why It Matters
Memory leaks are not only a beginner bug. Long-running applications, servers, games, and tools can slow down or crash if leaks accumulate. Even small leaks indicate unclear ownership.
The best fix is not "remember delete harder." The best fix is designing ownership so cleanup is automatic through containers, smart pointers, and RAII.
Syntax Block
std::vector<int> data(100); // automatic cleanup
auto object = std::make_unique<Type>(); // automatic delete
Explained Code
Example: Leak-Free Dynamic Storage
#include <memory> // std::unique_ptr, std::make_unique
#include <vector> // std::vector
void goodVector() {
std::vector<int> data(100); // owns dynamic array internally
data[0] = 42; // use storage safely
} // vector releases memory
class Report {};
void goodObject() {
auto report = std::make_unique<Report>(); // exclusive ownership
(void)report; // use object
} // unique_ptr deletes object
Both examples allocate dynamic resources internally, but cleanup is automatic when scope ends.
Key Points / Rules
- Avoid manual
newanddeletein normal application code. - Prefer
std::vectorfor dynamic arrays. - Prefer
std::unique_ptrfor exclusive heap objects. - Use RAII so exceptions do not skip cleanup.
- Treat leaks as ownership-design failures.
Common Mistakes
- Forgetting
deleteafternew. Manual matching is fragile. - Using
deleteinstead ofdelete[]. Arrays allocated withnew[]needdelete[]. - Leaking on exception paths. Code after a throw does not run.
- Thinking the operating system cleanup at program exit is enough. Long-running programs need correct cleanup during execution.
Quick Check
- Why does
std::vector<int>prevent the array leak? - How can an exception cause a leak with raw pointers?
Viva Answer
A memory leak happens when allocated memory is lost without cleanup. RAII, containers, and smart pointers prevent leaks by tying cleanup to object lifetime.