Monday, September 04, 2006

C/C++ CodeSec QuickTip#1 Memory Management

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

What to Check ForEnsure 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 handlingdelete 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.

WhyAlthough 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 Check1. Search for all locations in code where memory is being allocated.2. Identify how the corresponding memory is being deallocated.

How to FixIf 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.

The AppSec Guy

Jesus Christ, the Son of God became the Son of Man so that the sons of men may become sons of God. I, by the mercy and grace of Jesus Christ, am humbled that God is my Father. Greetings in His matchless name.