Skip to content
Related Articles

Related Articles

What is Memory Leak? How can we avoid?

View Discussion
Improve Article
Save Article
Like Article
  • Difficulty Level : Basic
  • Last Updated : 14 Jun, 2022

Memory leak occurs when programmers create a memory in heap and forget to delete it. 

The consequences of 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.
 

C




/* Function with memory leak */
#include <stdlib.h>
 
void f()
{
   int *ptr = (int *) malloc(sizeof(int));
 
   /* Do some work */
 
   return; /* Return without freeing ptr*/
}


To avoid memory leaks, memory allocated on heap should always be freed when no longer needed.
 

C




/* Function without memory leak */
#include <stdlib.h>
 
void f()
{
   int *ptr = (int *) malloc(sizeof(int));
 
   /* Do some work */
 
   free(ptr);
   return;
}


Program to Check whether the Memory is Freed or Not.

C++




// C Program to check whether the memory is
// freed or not
 
#include <iostream>
#include <cstdlib>
using namespace std;
 
int main()
{
  int* ptr;
  ptr = (int*) malloc(sizeof(int));
   
  if (ptr == NULL)
    cout << "Memory Is Insuffficient\n";
  else
  {
    free(ptr);
    cout << "Memory Freed\n";
  }
}
 
// This code is contributed by sarajadhav12052009


C




// C Program to check whether the memory is
// freed or not
 
#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");
  }
}
 
// This code is contributed by sarajadhav12052009


Output

Memory Freed


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!