0
0
CppDebug / FixBeginner · 4 min read

How to Fix Memory Leak in C++: Simple Steps and Examples

Memory leaks in C++ happen when you use new to allocate memory but forget to delete it. To fix this, always pair every new with a delete or use smart pointers like std::unique_ptr that automatically free memory.
🔍

Why This Happens

A memory leak occurs when your program allocates memory on the heap but never releases it. This means the memory stays reserved and cannot be used again, causing your program to use more and more memory over time.

In C++, this often happens when you use new to create objects but forget to call delete to free that memory.

cpp
#include <iostream>

int main() {
    int* ptr = new int(42); // allocate memory
    std::cout << *ptr << std::endl;
    // forgot to delete ptr
    return 0;
}
Output
42
🔧

The Fix

To fix the memory leak, you must free the memory you allocated with new by calling delete when you no longer need it. Alternatively, use std::unique_ptr which automatically deletes the memory when it goes out of scope.

cpp
#include <iostream>
#include <memory>

int main() {
    // Fix 1: Manual delete
    int* ptr = new int(42);
    std::cout << *ptr << std::endl;
    delete ptr; // free memory

    // Fix 2: Using smart pointer
    std::unique_ptr<int> smartPtr = std::make_unique<int>(42);
    std::cout << *smartPtr << std::endl;
    // no need to delete, automatic cleanup

    return 0;
}
Output
42 42
🛡️

Prevention

To avoid memory leaks in the future:

  • Always pair new with delete and new[] with delete[].
  • Prefer using smart pointers like std::unique_ptr or std::shared_ptr to manage memory automatically.
  • Use tools like Valgrind or sanitizers to detect leaks during development.
  • Follow RAII (Resource Acquisition Is Initialization) pattern to tie resource lifetime to object lifetime.
⚠️

Related Errors

Other common memory-related errors include:

  • Dangling pointers: Using memory after it has been freed. Fix by setting pointers to nullptr after deleting.
  • Double delete: Calling delete twice on the same pointer. Avoid by careful ownership management or smart pointers.
  • Buffer overflow: Writing outside allocated memory bounds. Prevent by careful indexing and using safe containers like std::vector.

Key Takeaways

Always free memory allocated with new by calling delete to avoid leaks.
Use smart pointers like std::unique_ptr to automate memory management.
Tools like Valgrind help find memory leaks during development.
Follow RAII pattern to tie resource lifetime to object lifetime.
Avoid related errors like dangling pointers and double deletes by careful coding.