Heap memory is allocated but never freed, causing the process to grow indefinitely.
A memory leak occurs when a program allocates heap memory with `new`/`malloc` but never releases it with `delete`/`free`. Over time, leaked memory accumulates and is never available to the rest of the system, which can slow down or crash long-running processes.
Causes include: forgetting to `delete` heap memory, using early returns or exceptions that skip the `delete` call, losing the only pointer to an allocation (so it can never be freed), or circular references in manually managed object graphs.
1#include <iostream>2 3void processData(bool condition) {4 int* buffer = new int[1000]; // Allocated on heap5 6 if (!condition) {7 // Early return without freeing 'buffer' — MEMORY LEAK!8 return;9 }10 11 // ... use buffer ...12 for (int i = 0; i < 1000; i++) buffer[i] = i;13 14 delete[] buffer; // Only reached if condition is true15}16 17int main() {18 for (int i = 0; i < 10000; i++) {19 processData(false); // Leaks 4000 bytes every call20 }21 return 0;22}1#include <iostream>2#include <memory>3#include <vector>4 5void processData_Fixed(bool condition) {6 // Fix 1: Use RAII with unique_ptr — automatically freed on scope exit7 auto buffer = std::make_unique<int[]>(1000);8 9 if (!condition) {10 return; // buffer is automatically freed here11 }12 13 for (int i = 0; i < 1000; i++) buffer[i] = i;14 // buffer is freed here automatically15}16 17void processData_Vector(bool condition) {18 // Fix 2: Use std::vector — no manual memory management19 std::vector<int> buffer(1000);20 21 if (!condition) {22 return; // vector cleans up automatically23 }24 25 for (int i = 0; i < 1000; i++) buffer[i] = i;26}27 28int main() {29 for (int i = 0; i < 10000; i++) {30 processData_Fixed(false); // No leak31 processData_Vector(false); // No leak32 }33 return 0;34}Simulate standard system builds to trigger compiler trace records and track memory crashes locally.
Each call to `processData(false)` allocates `1000 * sizeof(int)` bytes but returns early before reaching `delete[] buffer`. Over 10,000 calls, this leaks ~40MB. In a server or game running for hours, this grows unboundedly. The OS reclaims the memory when the process exits, but long-running programs can crash or degrade performance before then.