- This happens when the programmers allocate memory to the heap for some temporary use and then forget to delete it after using it.
- A memory leak occurs when a piece (or fragments) of memory previously allocated by a programmer is not properly deallocated by the programmer.
- Even if it is not in use by the memory program, it is still “reserved”, and that piece of memory can not be used by the program until it is properly deallocated by the programmer. So it’s called memory leak.
- Memory leak is a kind of bug that kills your app slowly by slowing down and eventually crashing it.
Memory leak Example:-
#include <stdlib.h>; void demo_memory_leak() { int *ptr = (int *) malloc(sizeof(int)); return; } int main() { // Call the function demo_memory_leak() to show memory leak demo_memory_leak(); return 0; }
- Here, within the function_memory_leak () function we have allocated 4 bytes on the heap, but forgot to release that memory before returning from function demo_memory_leak ().
- Apart from this, this demo_memory_leak() function has not highlighted the pointer for that allocated memory, so no one outside the demo_memory_leak() has access to that allocated memory.
- Therefore, the memory will leak by calling the demo_memory_leak () function.
Example to handle memory leaks:-
void demo_handle_mleak() { int *ptr = (int *) malloc(sizeof(int)); free(ptr); } int main() { // Call the function demo_handle_mleak() to handle the memory leak demo_handle_mleak() return 0; }
In the above example, no memory is useless because when we are coming out of the function, we are free the memory using the free()