Memory Leaks in C++

In this article, we will learn about memory leaks in C++.

We will see a basic introduction about memory allocation and its types. We will then proceed to learn about memory leaks in C++.

Memory Leaks in C++

Memory allocation:

Memory allocation is just basically assigning a memory space out of the others for storing a particular requirement like a variable. In C++, memory allocation can happen in two ways: Static and dynamic. When the user specifies the memory allocation before the program starts to run, that is, actually before execution or run time. For example if a user specifies an int array of size 50, it is a static memory allocation. This is handled using a stack.

But, when the allocation happens during runtime, during execution of our program, it is called as dynamic memory allocation. A vector in C++ is a popular example of dynamic memory allocation. It’s maximum size need not be specified. Elements can be added or deleted or inserted easily.

Memory leaks:

Now that we have seen what dynamic and static memory allocation are in C++, let us look at what memory leaks actually are. Let us say the programmer has dynamically allocated memory. It needs to be associated with a pointer. In C++ this is done using the new keyword. Example,

int* myptr = new int;

Once this memory that has been allocated is not in use by the program anymore, this allocation is practically useless. Let us say our program performs such an operation for about 1000000 times. The amount of memory that is wasted is enormous. Such useless memory going wasted is called memory leak.

Memory leak is very dangerous because this disgustingly large amount of memory allocation may practically cause the device to crash and malfunction terribly. This is not desired for any kind of application either experimental or in actual deployment especially when dealing with huge data or many operations.

A very simple solution is to basically to de-allocate the useless memory. In C++, this is done using the delete keyword. Example,

delete myptr;

If we are trying to do this for an array, use delete[].

To avoid memory leaks:

To avoid such memory leaks, it is the duty of the programmer to take care of memory allocations. As a rule, for every ‘new’ you use make sure you use the ‘delete’ keyword so that you don’t miss out on useless memory allocations. Even if you are reallocating memory to it make sure you have deleted it or else it will exist twice. Also, in the process don’t lose track of the pointers associated with them.

Detecting memory leaks can be painful in large applications. If we generally follow these methods of allocating and de-allocating, we can overcome memory leak troubles.

Leave a Reply

Your email address will not be published. Required fields are marked *