Monday, September 04, 2006

C/C++ CodeSec QuickTip#1 Memory Management

Applies to
Whenever some memory is being allocated using new, for example.

What to Check For
Ensure that delete will be called properly. Ensure that all exceptions are being caught for code following the new. Consider the following code:
int * myint = new int;
//some work - with no exception handling
delete myint;
What will happen if an exception occurs in the second line of code? The delete will not be called and a memory leak will exist.

Why
Although you may take great pains to match new and delete, the delete may end up not being called due to very different reasons.

How to Check
1. Search for all locations in code where memory is being allocated.
2. Identify how the corresponding memory is being deallocated.

How to Fix
If ever you need to use new and delete, do ensure to new in the constructor and delete in the destructor. This is the only guarantee that the memory will be freed.
If you cannot always do a new in the constructor, then ensure that there arent any alternate code paths. For example, change of logic in code that prevents the deallocation code from executing. Another example (as described above) is when an unhandled exception occurs and the deallocation code is altogether skipped.

Problem Example
int * myint = new int;
//some work - with no exception handling
delete myint;

Solution Example
int * myint = new int; //FIX: Move this code to the constructor
//some work - with no exception handling
delete myint; //FIX: Move this code to the constructor

1 comment:

Deepshikha said...

I think you made a typo error in the last line of your article. Should it not have been:
delete myint; //FIX: Move this code to the destructor.
Nice article though!