0
0
C++programming~5 mins

Memory leak concept in C++

Choose your learning style9 modes available
Introduction

A memory leak happens when a program keeps using memory but never gives it back. This can make the program slow or crash.

When you want to understand why your program is getting slower over time.
When your program uses a lot of memory and you want to find mistakes.
When you want to learn how to manage memory properly in C++.
When debugging programs that run for a long time and suddenly stop working.
When you want to write better, safer C++ code.
Syntax
C++
int* ptr = new int[10];
// use ptr
// forgot to delete[] ptr;

new allocates memory on the heap.

If you don't use delete or delete[] to free it, memory leaks happen.

Examples
This creates one integer in memory but never frees it, causing a memory leak.
C++
int* ptr = new int;
*ptr = 5;
// forgot to delete ptr;
This correctly frees the memory allocated for an array, avoiding a leak.
C++
int* arr = new int[5];
// use arr
delete[] arr;
Sample Program

This program creates an array of 3 integers but never frees the memory. It prints the values correctly but leaks memory.

C++
#include <iostream>

int main() {
    int* leak = new int[3];
    leak[0] = 1;
    leak[1] = 2;
    leak[2] = 3;
    std::cout << "Values: " << leak[0] << ", " << leak[1] << ", " << leak[2] << std::endl;
    // Memory leak here: no delete[] for leak
    return 0;
}
OutputSuccess
Important Notes

Always match each new with a delete and each new[] with a delete[].

Using smart pointers like std::unique_ptr can help avoid leaks automatically.

Memory leaks may not crash your program immediately but can cause problems over time.

Summary

Memory leaks happen when allocated memory is not freed.

They make programs use more memory and can cause slowdowns or crashes.

Always free memory you allocate with new or use smart pointers.