Memory Leak: Scenario #1

Many a times we write code like this:

int *pData1 = NULL;
int *pData2 = NULL;

pData1 = new int [ n ];
pData2 = new int [ m ];

if ( pData1 && pData2 )
{
// Use pData1 and pData2

delete[ ] pData1;
delete[ ] pData2;
}

Is there anything wrong with this code? If you think there is nothing wrong with this code, well …

Let us analyze what is wrong here.

The condition in if statement makes sure we use pData1 and pData2 only when both of them are assigned valid addresses after allocating memory successfully, using new operator. When memory allocation is successful, for both pData1 and pData2, we use the pointers and when not required anymore, we release the allocated memory using delete operator.

In case memory allocation fails, for both pData1 and pData2, we never enter the if statement block. So everything looks fine here?

No, what if only one allocation fails, for either pData1 or pData2? Due to the condition in if statement we will not enter the if statement block, resulting in leaking memory which was allocated using new operator.

So what is the correct way to write the above code snippet? Instead of releasing memory inside if statement block we will release the memory out the if statement block. But doing this won’t we will be releasing memory even when it is not allocated? So we will release the memory outside if statement block but conditionally, after checking if it is allocated or not. Below is the modified code snippet.

int *pData1 = NULL;
int *pData2 = NULL;

pData1 = new int [ n ];
pData2 = new int [ m ];

if ( pData1 && pData2 )
{
// Use pData1 and pData2
}

if ( pData1 )
{
delete[ ] pData1;
}

if ( pData2 )
{
delete[ ] pData2;
}