Definition
A memory leak occurs when a program allocates memory dynamically (using operators like new or functions such as malloc) but fails to release it back to the system after use. As a result, the reserved block of memory remains inaccessible to the program yet unavailable for future allocations. Over time, this wasted memory can accumulate, leading to reduced performance or even program crashes.
In C++, there is no automatic garbage collection. It means that any memory that is dynamically allocated by the programmer needs to be freed after its usage manually by the programmer. If the programmer forgets to free this memory, it will not be deallocated till the program lives and will be unavailable to other processes. This is called memory leak.
How It Happens in C++
1.Dynamic Allocation Without Deallocation
int* ptr = new int(10);
// Forgot to delete ptr
- Here, memory is allocated for an integer, but since delete ptr; is missing, the memory remains occupied until the program terminates.
2.Lost References
int* arr = new int[5];
arr = nullptr;
// Original pointer lost
- The pointer to the allocated block is overwritten, making it impossible to free the memory later.
Consequences-
1.Gradual increase in memory usage during program execution.
2.Slower performance due to reduced available memory.
3.In severe cases, the operating system may terminate the program for exhausting resources.
Prevention Strategies-
1.Always pair new with delete and new[] with delete[].
2.Use Smart Pointers (std::unique_ptr, std::shared_ptr). These automatically manage memory and reduce the risk of leaks.
3.Adopt RAII (Resource Acquisition Is Initialization). Bind resource management to object lifetime so that memory is released when objects go out of scope.
4.Employ Tools. Utilities like Valgrind or AddressSanitizer can detect leaks during testing.
Top comments (0)