Memory leak happens in a program when memory is dynamically (e.g., with malloc or new) requested but not given back (e.g., through free or delete) when the memory is not needed anymore. These memory reservations, not yet released, can pile up as time passes and decrease the total amount of accessible memory for other processes and even for the entire system. Such can result in system slowdown, performance loss, or even process crashes when running out of available memory.
Key Characteristics of Memory Leaks:
Unreleased Memory: Memory is allocated but not freed, even after it is no longer in use.
Gradual Accumulation: Memory usage increases over time as the program continues to run.
Unintentional: The program loses references to the allocated memory, making it impossible to free.
Common Causes:
Forgotten Deallocation: Failing to call free or delete after using malloc or new.
Lost References: Overwriting pointers to allocated memory without freeing the original memory.
Circular References: In languages with garbage collection, objects reference each other, preventing the garbage collector from reclaiming memory.
Example (C++):
void memoryLeakExample() {
int* ptr = new int(10); // Memory allocated
// No delete statement, causing a memory leak
}