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
C++ References and const References
C++ Pointers
C++ Dynamic Memory: new, delete and Smart Pointers
Exercises & Assignments
Swap two numbers using a reference function
Manage a resource with unique_ptr
Interview Questions & Answers
What is the difference between a reference and a pointer in C++?
What is the difference between new and malloc in C++?
What is a memory leak in C++ and how to avoid it?
What is nullptr in C++? What is the difference from NULL?
What is RAII in C++?
What is the difference between unique_ptr, shared_ptr and weak_ptr?
What is const correctness in C++?