What is a memory leak in C++ and how to avoid it?
A memory leak happens when you allocate memory with new and lose the pointer without delete. The program uses more and more memory.
#include <iostream>
#include <memory>
int main() {
int* leak = new int(5);
leak = nullptr; // the address is lost: a leak (the memory is never freed)
auto safe = std::make_unique<int>(5); // freed automatically
std::cout << *safe << '\n';
}
Output
5
How to avoid it: use std::unique_ptr and std::shared_ptr, use containers (vector, string) and follow RAII. Tools like AddressSanitizer (-fsanitize=address) and Valgrind find leaks. See Smart Pointers.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |