C++ Memory Leaks
In this page:
What is a Memory Leak?
A memory leak occurs when heap memory allocated with new is never released with a matching delete, so the program loses any way to free it even though it's no longer using it. A long-running program with leaks gradually consumes more and more RAM until performance degrades or the system runs out of memory.
Example: What is a Memory Leak?
#include <iostream>
int main() {
int *ptr = new int(5);
// missing delete ptr; here would leak this memory
delete ptr;
std::cout << "Freed correctly" << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Reassigning Pointers without Deallocating
If you reassign a pointer to a new address without first calling delete on the old one, the original memory block becomes unreachable -- there's no remaining pointer anywhere in the program that references it, so it can never be freed, even though it's technically still "in use" as far as the OS is concerned.
Example: Reassigning Pointers without Deallocating
#include <iostream>
int main() {
int *ptr = new int(5);
delete ptr;
ptr = new int(10);
std::cout << *ptr << std::endl;
delete ptr;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Leaks inside Functions
Allocating memory inside a function with new and storing the address only in a local pointer variable means that address is lost the moment the function returns, unless you explicitly return the pointer or store it somewhere that outlives the function call. Otherwise that memory leaks silently on every call.
Example: Leaks inside Functions
#include <iostream>
int *createValue() {
int *ptr = new int(42);
return ptr;
}
int main() {
int *result = createValue();
std::cout << *result << std::endl;
delete result;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Dynamic Arrays and Incorrect Delete
Freeing a dynamically allocated array with a plain delete instead of delete[] only destructs and frees the first element correctly -- the rest of the array's memory is never properly released, causing a partial leak that's easy to miss since the program doesn't crash immediately.
Example: Dynamic Arrays and Incorrect Delete
#include <iostream>
int main() {
int *arr = new int[5];
delete[] arr;
std::cout << "Array freed correctly" << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Best Practices for Prevention
The most reliable way to avoid leaks is to minimize how long you hold raw new/delete pairs, and prefer C++ smart pointers (unique_ptr, shared_ptr) which automatically call delete when they go out of scope -- turning manual bookkeeping into something the compiler enforces for you.
Example: Best Practices for Prevention
#include <iostream>
#include <memory>
int main() {
std::unique_ptr<int> ptr = std::make_unique<int>(5);
std::cout << *ptr << std::endl;
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: