What is Memory Leak in C++

What is?

Memory leaks occur when previously allocated memory is not deallocated by programmer.

When we allocate some memory to variable, objects etc it is reserved for that and cannot be used for other purpose, so if we cannot deallocate it properly, that block of memory get wasted and we call it "MEMORY LEAK". Because it is like  a leaky faucet from which memory is wasted.

What is the problem?

Memory leak problem sometime become the cause of "Program CRASH".
HOW? If there is enough memory in program that hasn't been deallocated, then it may possible that there is no memory left in the program for further processing, which in turn either slow down the program performance or causes the program to crash.

 

Memory leak problem in C++

void memoryleakdemo()
{
   int *val= new int;
   a=10;
   *val=20;
}


Above code block is suffer from memory leak. Because the memory allocated to pointer "val" is not deallocated. Hence pointer goes out of scope( The code block {}.

For a better practice it is require that we carefully handle pointers and deallocate memory when we are not using. 

For deallocation in C++ we use delete(), and in C we use free()

The corrected version of above code is given below

void memoryleakdemo()
{
   int *val= new int;
   a=10;
   *val=20;
  delete val;
  val =NULL;
}

Share this post and spread the knowledge --->

No comments:

Post a Comment