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
...
| Attachment | Size |
|---|---|
| RArrayContentProtection.zip | 3.58 KB |
Comments
Not when you need to pass the array further
True, but in case of "RStringArray array", the array object would be allocated on stack and would be destroyed, when you exit the function. Usually it is ok, whoever needs the RStringArray can copy it.
However I had to work with an API that wanted to take the ownership over the passed RStringArray. Therefore I had to allocate it on the heap and ran into this somewhat tricky protection issue.
I considered this possibility.
As far as I understand, there is nothing wrong about pushing (and later deleting) the NULL object. Deleting NULL pointers is always safe.
I guess you cannot use the "new (ELeave)" for RObjects. AFAIK, this operator is defined for CBase only.
You are right. Corrected.
CleanupClosePushing dereferenced NULL works (at least on emulator), but I really missed the possibility of null pointer exception later. I also rechecked the "new (ELeave)" overloads and they really can be used with non C-classes.
I already corrected both this post and the attached code example. Thank you, Tote.
Nice to meet you,
Nice to meet you, Török!
Great to have a networking expert participating the site discussions! :)