CleanupClosePushL

Tip: protect both the RArray and its contents

Update: "new (ELeave) RStringArray" was missing the "ELeave" (thanks to Tote)

Lately I worked with the API that required passing the RPointerArray allocated on the heap so that ownership was passed to that API. It is quite a rare case, but demonstrates nicely how tricky the CleanupStack protection can sometimes be. Note the order of pushing to the cleanup stack. If CleanupClosePushL was called first and leave happened during the CleanupStack::PushL, memory leak would occur.


// Local Functions
typedef RPointerArray RStringArray;
...
HBufC* element1 = HBufC::NewLC( 10 );
HBufC* element2 = HBufC::NewLC( 20 );
RStringArray* array = new (ELeave) RStringArray;
// Protect the allocated heap mem
CleanupStack::PushL( array );
// Protect the kernel handle/array contents
CleanupClosePushL( *array );
array->AppendL( element1 );
array->AppendL( element2 );

CleanupStack::PopAndDestroy( array ); // Close the array
CleanupStack::PopAndDestroy( array ); // And free the heap mem
...

Syndicate content