What is a memory leak in C++, and provide an example?

A memory leak occurs when a piece (or pieces) of memory that was previously allocated by a programmer is not properly deallocated by the programmer. Even though that memory is no longer in use by the 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. That’s why it’s called a memory leak – because it’s like a leaky faucet in which water is being wasted, only in this case it’s computer memory.

What problems can be caused by memory leaks?

The problem caused by a memory leak is that it leaves chunk(s) of memory unavailable for use by the programmer. If a program has a lot of memory that hasn’t been deallocated, then that could really slow down the performance of the program. If there’s no memory left in the program because of memory leaks, then that could of course cause the program to crash.

An example of a memory leak in C++

Here is an example of a memory leak in C++:

Out of Scope Pointer

void memLeak( )
{
  int *data = new int;
  *data = 15;
}

So, the problem with the code above is that the “*data” pointer is never deleted – which means that the data it references is never deallocated, and memory is wasted.

Hiring? Job Hunting? Post a JOB or your RESUME on our JOB BOARD >>

Subscribe to our newsletter for more free interview questions.