Memory leaks can be tricky to identify because they don't typically cause your program to immediately malfunction. Instead, they gradually consume more and more memory over time.
Here are a few strategies for identifying memory leaks:
new
 has a corresponding delete
.std::unique_ptr
, std::shared_ptr
, std::vector
, etc., can dramatically reduce the likelihood of memory leaks, as they handle deallocation for you.Here's an example of a memory leak:
void func() {
int* ptr = new int(10);
return; // Leak: ptr is never deleted
}
And here's how you might fix it:
void func() {
int* ptr = new int(10);
// ...
delete ptr;
}
Or, even better, with a smart pointer:
#include <memory>
void func() {
std::unique_ptr<int> ptr{
std::make_unique<int>(10)};
// ...
// ptr will be automatically deleted
}
Remember, every new
should have a corresponding delete
, and if you find manual memory management cumbersome, use smart pointers and containers instead.
Answers to questions are automatically generated and may not have been reviewed.
Learn about dynamic memory in C++, and how to allocate objects to it using new
and delete