Contents |
An essential characteristic of Symbian OS is that it is designed for devices where the amount of memory and resources available is limited.So, it needs a very efficient memory management.Run-time errors may occur in any application due to lack of resources: for example, a machine runs out of memory or fails to access a hardware resource. There errors are known as exceptions and it is impossible to prevent them occurring by modifying the program. Therefore, programs should be able to recover from exceptions when they occur.
So, key requirements for Symbian OS for good memory management are:
memory is allocated
and stable state and make sure that you clean up all resources allocated during that operation.
On a Stack:
On a Heap:
Example:
TInt i = 0;
CMyObj* obj = new (ELeave) CMyObj;
Here, i is stored on a stack and obj is pointed to heap memory.
When objects are declared on the Stack, they are deleted automatically when the object goes out of scope. The default stack size is 8Kb, but it is possible to increase this by use of the epocstacksize statement in the project (.mmp file). Use of the project file will be covered in a subsequent module. (Note: changing the stack size will have no effect when using the Emulator).
By contrast, when an object is allocated dynamically on the Heap, it needs to be specifically deleted by the programmer using the delete keyword. If it isn't a memory leak occurs. The size of heap will vary according to the memory available on a given device, but should exceed 0.5Mb.
Leave Examples
return new (ELeave) TUint8[100];
User::Leave(KErrNotFound); // from e32std.h
User::LeaveNoMemory();
void CMyClass::SetCallbackL(MNotify* aNotify)
{
User::LeaveIfNull(aNotify);
...
RFs fileServer; // handle to file server
TInt error = fileServer.Connect();
User::LeaveIfError(error);
Cleanup stack support for non-CBase classes
Using Cleanup Stack
CleanupStack::PushL(ptr) for pointers – memory will be deleted in
the event of a Leave
CleanupClosePushL(handle) for handles – handle will be closed in
the event of a Leave
CleanupStack::Pop(pointer) to remove the top item
CleanupStack::PopAndDestroy(pointer) to remove and
delete/close the item
• that object is referred to by a local pointer only AND
• a function that can leave is called during the lifetime of that object.
Example:
Here, if ConstructL() Leaves, self will be automatically deleted:
CMyClass* CMyClass::NewL(TInt aBufSize)
{
CMyClass* self = new (ELeave) CMyClass;
CleanupStack::PushL(self);
self->ConstructL(aBufSize);
CleanupStack::Pop(self);
return self;
}
NewL() and NewLC()
These static functions perform both construction phases in one go. Providing NewL() or NewLC() functions as part of a class makes it easier to use that class. NewLC() would typically be used where one function contains a series of automatic variables (which point to heap memory), to save pushing each one onto the cleanup stack.
How to log heap allocations, Symbian 9
--
No related wiki articles found