Back to Windows

Its being a long time ever since I used an Operating System from Microsoft for something more than just an environment to develop C/C++ applications. During my college days and initial years in my first job I used to dig into the skin of Operating Systems like MS-DOS, Windows 95, Windows NT but ever since then, as I switched jobs due to the job requirement that hobby came to a grinding halt.

Couple of days back I got a chance to venture out into the wild once again. No prize for guessing that I grabbed this oportunity with both hands (unfortunatly we humans got only two hands). Today on the occasion of my b’day I got a confirmation that I’ll be digging into some of the new features of yet to be released Operating System from Microsoft, Vista codename Longhorn.

So here is what Wikipedia says about the new features of Microsoft Vista.

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;
}