Memory Leaks
What is a memory leak, and how can it be prevented in C++?
A memory leak occurs when dynamically allocated memory is not properly deallocated, leading to a gradual loss of available memory. This can happen when:
- Forgetting to use
delete
on dynamically allocated memory - Losing track of pointers to dynamically allocated memory
- Not freeing memory in all possible code paths (e.g., exceptions)
Example 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++:
- Always deallocate dynamically allocated memory using
delete
when it's no longer needed. - Use smart pointers (e.g.,
unique_ptr
,shared_ptr
) that automatically handle memory deallocation. - Be cautious when using raw pointers, and ensure proper deallocation in all code paths.
- Use memory profiling tools to detect and diagnose memory leaks.
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.
Memory Management and the Stack
Learn about stack allocation, limitations, and transitioning to the Free Store