Memory leak occurs when programmers create a memory in a heap and forget to delete it.
The consequence of the memory leak is that it reduces the performance of the computer by reducing the amount of available memory. Eventually, in the worst case, too much of the available memory may become allocated and all or part of the system or device stops working correctly, the application fails, or the system slows down vastly.
Memory leaks are particularly serious issues for programs like daemons and servers which by definition never terminate.
Example of Memory Leak
C
#include <stdlib.h>
void f()
{
int * ptr = ( int *) malloc ( sizeof ( int ));
return ;
}
|
How to avoid memory leaks?
To avoid memory leaks, memory allocated on the heap should always be freed when no longer needed.
Example: Program to Release Memory Allocated in Heap to Avoid Memory Leak
C
#include <stdlib.h>
void f()
{
int * ptr = ( int *) malloc ( sizeof ( int ));
free (ptr);
return ;
}
|
Example: Program to Check Whether the Memory is Freed or Not
C
#include <stdio.h>
#include <stdlib.h>
int main( void )
{
int * ptr;
ptr = ( int *) malloc ( sizeof ( int ));
if (ptr == NULL)
printf ( "Memory Is Insuffficient\n" );
else {
free (ptr);
printf ( "Memory Freed\n" );
}
}
|
C++
#include <iostream>
using namespace std;
int main()
{
int * ptr = new int ;
if (ptr == NULL)
cout << "Memory Is Insuffficient\n" ;
else {
delete ptr;
cout << "Memory Freed\n" ;
}
}
|