A memory leak occurs when dynamically allocated memory is not properly deallocated, leading to a gradual loss of available memory. This can happen when:
delete
 on dynamically allocated memoryExample of a memory leak:
void function() {
int* ptr = new int;
// ...
// Forgot to delete ptr, causing a memory leak
return;
}
To prevent memory leaks in C++:
delete
 when it's no longer needed.unique_ptr
, shared_ptr
) that automatically handle memory deallocation.Example of preventing a memory leak with a smart pointer:
#include <memory>
void function() {
auto ptr = std::make_unique<int>();
// ...
return; // ptr is automatically deallocated
}
By adopting good memory management practices and utilizing smart pointers, you can prevent memory leaks and ensure your C++ programs use memory efficiently.
Answers to questions are automatically generated and may not have been reviewed.
Learn about stack allocation, limitations, and transitioning to the Free Store