0
0
CppConceptBeginner · 3 min read

What is Memory Leak in C++: Explanation and Example

A memory leak in C++ happens when a program allocates memory using new but never releases it with delete. This causes the program to use more memory over time, which can slow down or crash the system.
⚙️

How It Works

Imagine you have a box where you keep your toys. Every time you get a new toy, you put it in the box. But if you forget to take out broken toys or toys you no longer play with, the box will fill up and you won't have space for new toys. In C++, memory works similarly.

When your program needs space to store data, it asks the computer for memory using new. If you forget to give that memory back using delete, the computer keeps that memory reserved even if you don't use it anymore. This leftover memory is called a memory leak.

Over time, these leaks add up and your program uses more and more memory, which can slow down your computer or cause the program to crash because it runs out of memory.

💻

Example

This example shows a memory leak because the allocated memory is never freed.

cpp
#include <iostream>

int main() {
    int* ptr = new int(10); // allocate memory
    std::cout << "Value: " << *ptr << std::endl;
    // forgot to delete ptr, memory leak occurs here
    return 0;
}
Output
Value: 10
🎯

When to Use

Understanding memory leaks is important when writing programs that run for a long time or use a lot of memory, like games, servers, or apps that handle large files. Avoiding leaks helps keep your program fast and stable.

Always pair every new with a delete to free memory when you no longer need it. Tools like smart pointers in modern C++ can help manage memory automatically and prevent leaks.

Key Points

  • A memory leak happens when allocated memory is not freed.
  • It causes your program to use more memory over time.
  • Always free memory with delete after new.
  • Use smart pointers to help manage memory safely.

Key Takeaways

Memory leaks occur when allocated memory is not released with delete.
Leaked memory reduces available memory and can crash programs.
Always free memory after allocation to avoid leaks.
Smart pointers in C++ help prevent memory leaks automatically.