SlideShare a Scribd company logo
Symbian OSMemory Managementv2.0a – 21 May 20081Andreas Jakl, 2008
DisclaimerThese slides are provided free of charge at http://www.symbianresources.com and are used during Symbian OS courses at the University of Applied Sciences in Hagenberg, Austria ( http://www.fh-hagenberg.at/ )Respecting the copyright laws, you are allowed to use them:for your own, personal, non-commercial usein the academic environmentIn all other cases (e.g. for commercial training), please contact andreas.jakl@fh-hagenberg.atThe correctness of the contents of these materials cannot be guaranteed. Andreas Jakl is not liable for incorrect information or damage that may arise from using the materials.Parts of these materials are based on information from Symbian Press-books published by John Wiley & Sons, Ltd. This document contains copyright materials which are proprietary to Symbian, UIQ, Nokia and SonyEricsson. “S60™” is a trademark of Nokia. “UIQ™” is a trademark of UIQ Technology. Pictures of mobile phones or applications are copyright their respective manufacturers / developers. “Symbian ™”, “Symbian OS ™” and all other Symbian-based marks and logos are trademarks of Symbian Software Limited and are used under license. © Symbian Software Limited 2006. Andreas Jakl, 20082
ScheduleLeaves, Panics and TRAP(D)CleanupstackObjectconstructionusingELeaveTwo-phaseconstructionDebugging toolsAndreas Jakl, 20083
Leaves & PanicsHandling problemsAndreas Jakl, 20084
Exceptions – JavaTry & Catch for handling exceptionsFunctions can throw “Exceptions”Andreas Jakl, 20085Integer Class…static intparseIntthrowsNumberFormatException {…}…Calling functionTry {int x = Integer.parseInt(“1234”);} catch (NumberFormatException e) {System.out.println(“Unable to convert this String to a number.”);}
Leave – SymbianTRAP(D) catches exceptions (“Leave”)Functions send out leaveFunction name marked by an L-suffixAndreas Jakl, 20086The TRAP(D) macros are defined in e32cmn.hMain-FunctionTRAPD(err, DoExampleL());if (err)    {    console->Printf(KTxtFailed, err);    }DoExampleL()-FunctionvoidDoExampleL()    {RFsfsSession;  // Connect to the file serverUser::LeaveIfError(fsSession.Connect()); // …fsSession.Close();    }TRAPD-Makro declares err as TInt and = KErrNoneLeaves if the Connect() function does not return KErrNone
Central ExceptionHandlingAndreas Jakl, 20087New (ELeave) … … NewL() …    … User::Leave() …… ConstructL() …F6L()F7L()F8L()F9L()F5L()F5L() … … F6L() ….… F8L() ….F3L()F4L()F0L()F2L()… F3L() …F4L() …F1L()TRAPD(err, F2L());if(err) …
Handling LeavesTry to implement central leave-handlingIf leave not handled by your code  error-message shown by the UI-framework!Therefore: Only handle leaves yourself if they influence your applicationAndreas Jakl, 20088
When can a function leave?Caused by your own code:User::Leave(), User::LeaveIfError(), User::LeaveNoMemory() or User::LeaveIfNull()Failed object-constructionwhen using the “new (ELeave)”-operatorCalling a function that potentially causes a leavee.g. x->DoSomethingL()Andreas Jakl, 20089
Details: Causing a LeaveUser::Leave(TIntaReason)Error code (aReason) = value that will be received by TRAPCauses leave in any caseUser::LeaveIfError(TIntaReason)Causes leave if parameter is negative, e.g.:TIntfoundAt = iElementArray.Find(example, aRelation);User::LeaveIfError(foundAt);	// Leaves if foundAt == KErrNotFound (-1)User::LeaveNoMemory()Is the same as: User:Leave(KErrNoMem);User::LeaveIfNull(TAny* aPtr)Andreas Jakl, 200810
TRAP / TRAPDTwo trap harness macros:TRAP: declares the variable in which the leave code is returnedTRAPD: declare a TIntvariable yourselfIf a leave occurs inside MayLeaveL(), which is executed inside the harness, the program code will return immediately to the TRAP harness macroThe variable result will contain the error code associated with the leave or will be KErrNoneif no leave occuredAndreas Jakl, 200811TRAPD(result, MayLeaveL());if (KErrNone!=result)...is equivalent to:TIntresult;TRAP(result, MayLeaveL());if (KErrNone!=result)...
TipsAndreas Jakl, 200812XvoidInsertData()    {TInt err;    TRAP(err, iData->InsertL(23));if (err) { ... }    TRAP(err, iData->InsertL(24));if (err) { ... }    }TRAPs are expensiveDon’t use several TRAPs right after each otherInstead:Make the function leave (append an L to the function name)Handle all errors in a single TRAP-call one level above!In UI apps, many leaves don’t have to be handled by you  they can go up to the topmost level (= Active Scheduler)prefervoidHandleCommand()    {    TRAPD(err, InsertDataL());if (err) { ... }    }voidInsertDataL()    {iData->InsertL(23));iData->InsertL(24));    }
Panics... cannot be caught and handled!Terminates thread (= usually the whole application)Use them for checking code logic onlyCan also be sent out by the system for critical errorsIf a panic happens:Make sure you fix it, as you can’t handle it!Andreas Jakl, 200813// Stray signal detected!_LIT(KMsgStraySignal, "Stray signal\n");User::Panic(KMsgStraySignal, 1);		// Panic with code 1
Resource HandlingStack, Heap and the Cleanup StackAndreas Jakl, 200814
Practice in a NutshellAll strategiesarepresent in thisfunction:Andreas Jakl, 200815CClass* CClass::NewL(TIntaInt, CBase& aObj){CClass* self = new (ELeave) CClass(aInt);CleanupStack::PushL(self);self->ConstructL(aObj);CleanupStack::Pop(self);returnself;}
Recap: StackAndreas Jakl, 200816// Stack (1)voidCTest::F1(){TInt x = 0;TInt y = 1;for(x = 0; x < 10; x++)		y++	y = y + F2(); // Stack (4)}// Stack (5)TIntCTest::F2(){TInt a = 2;TInt b = 1;return a + b;   // Stack (3)}Stack (2)Stack(5)Stack(1)TInt yTInt xF1Stack(2)TInt yTInt xF1Stack(4)TInt bTInt aF2TInt yTInt xF1Stack(3)
Recap: HeapUse for:Objects that need a lot of memory ( stack-size is limited!)Required amount of memoryonlyknown at runtimeScope of heap-objects is not limited to a functionUse pointers to pass to other functions/objectsAndreas Jakl, 200817
MotivationSymbian OS designed to run for many years No opportunity to reclaim leaked memory through regular restarts!Small memory leaks accumulate over timeWe only have a small memory to start withTherefore: Simply write perfect, leak-free code!Andreas Jakl, 200818
Motivation – How?By keeping track of all allocated objects!By making sure:All heap-objects are pointed to by at least one pointer, all the time – even in the constructor of an object!Free heap memory as soon as possible after use.Andreas Jakl, 200819
The Cleanup StackSafeguardAndreas Jakl, 200820
Resource Handling – Rule 1Andreas Jakl, 200821Every local pointer to an instance of a heap-based object also has to be pushed on the cleanup stack, if there‘s the risk that the pointer gets lost because of a leave.
Cleanup StackSituation: function creates local heap-objectBefore code gets to the delete-statement: errorFunction is left (Leave)Pointer-address on the stack is freedObject itself is orphaned memory leak!Andreas Jakl, 200822voidCImage::DoSomethingDangerousL()    {    User::Leave(KErrNotFound);    }CImagevoidCMyObj::DoSomethingL(){}CImage* img = new (ELeave) CImage();img->DoSomethingDangerousL();deleteimg;img = pointer on the stack to an instance on the heap
Cleanup StackMemory situation if a leave occurs:Andreas Jakl, 200823!XXimgHeapStackObject stays on the heap;Pointer to delete the instance is lostmemory leak
Cleanup StackSolution: Cleanup StackAndreas Jakl, 200824void CMyObj::DoSomethingL(){CImage* img = new (ELeave) CImage();CleanupStack::PushL(img);img->DoSomethingDangerousL();CleanupStack::PopAndDestroy();}imgCleanupStackXXimgHeapStackWhen no leave occurs: object still has to be deleted by you + removed from the cleanup stack!Cleanup stack saves a second pointerto the object on the heap.
AdvancedCleanupAndreas Jakl, 200825RFileForresourcesthathavetobeclosed / freed(e.g.: files, sockets, …)Close(): CleanupClosePushL(T&)Release(): CleanupReleasePushL(T&)Destructor: CleanupDeletePushL(T*)Close()TCleanupOperationTAny* aPtr…TCleanupItemCleanupStack
AdvancedCleanup – ExampleAndreas Jakl, 200826voidCMyClass::TransferDataL()    {RSocketServsocketServer;    // Connect to SocketServer    User::LeaveIfError( socketServer.Connect() );    // Make sure Close() is called at the endCleanupClosePushL( socketServer );// …CleanupStack::PopAndDestroy();  //  socketServer    }
Cleanup Stack and Ownership TransferIt should never be possible for an object to be deleted more than once!Andreas Jakl, 200827voidTransferOwnershipExampleL()    {    // The stack variable ptr points to memory allocated on the heapCItem* ptr = new (ELeave) CItem();    // The following function may leave -> place the pointer on the    // cleanup stack, so that the heap memory is freed in case     // AppendL() leaves.CleanupStack::PushL(ptr);    // iItemPtrArray takes ownership of the CItem object.    // This could fail, as it needs to allocate a new slot to store the pointer,     // therefore the object was placed on the cleanup stack in advanceiItemPtrArray->AppendL(ptr);    // iItemArray now owns the heap object, so ptr may be safely popped off the stack.    // It shouldn’t be destroyed, as this would make the item in iItemPtrArray invalid!CleanupStack::Pop(ptr);    }
Practice in a NutshellStrategiesexplaineduptonow:Andreas Jakl, 200828CClass* CClass::NewL(TIntaInt, CBase& aObj){CClass* self = new (ELeave) CClass(aInt);CleanupStack::PushL(self);self->ConstructL(aObj);CleanupStack::Pop(self);returnself;}
Resource Handling – Rule 2Andreas Jakl, 200829Never push instance variables on the cleanup stack!The owning class is also on the cleanup stack somewhere (at least indirectly). This would lead to a double deletion of the object pointed to by the instance variable  Panic!
Coding Error ExampleAndreas Jakl, 200830class CSimple : CBase    {       public:    ~CSimple();    void MayLeaveFuncL();private:    void PrivateMayLeaveL();CItem* iItem;    };CSimple* simple = new (ELeave) CSimple();CleanupStack::PushL(simple);1. CSimple is created and pushed onto the cleanup stack as the next function may leaveTRAPD(res,simple->MayLeaveFuncL());...2. A leaving method is called on simplevoid CSimple::MayLeaveFuncL()    {iItem= new (ELeave) CItem();CleanupStack::PushL(iItem);PrivateMayLeaveL();CleanupStack::Pop(iItem);    }3. The member variable is pushed onto the clean up stack (oops!)5. The TRAP does the right thing and clears the cleanup stack; i.e. CSimple::iItem is deleted 4. What happens if a leaves occurs? ...6. The code logic completes with the popping and deleting of the simple object.CleanupStack::PopAndDestroy(simple);CSimple::~CSimple    {    delete iItem;    }BUT this calls the CSimple destructor, which deletes the iItem which has already been deleted by the TRAP  7. PANIC!Example taken from theSymbian Academy slides
Object ConstructionLeave-handling duringAndreas Jakl, 200831
New Objectsnew-operator allocates memory and runs constructorReturns null-pointer if object creation fails(e.g. not enough memory) manual test required to see if it was successful – no automated leave!Andreas Jakl, 200832void CMyObj::DoSomethingL()    {CImage* img = newCImage();    if (img)         {CleanupStack::PushL(img);img->DoSomethingDangerousL();CleanupStack::PopAndDestroy();}     else        {        User::LeaveNoMemory();        }    }
New Objects – ELeaveAndreas Jakl, 200833void CMyObj::DoSomethingL()    {CImage* img = newCImage();    if (img)         {CleanupStack::PushL(img);img->DoSomethingDangerousL();CleanupStack::PopAndDestroy();}     else        {        User::LeaveNoMemory();        }    }void CMyObj::DoSomethingL()    {CImage* img = new (ELeave)CImage();CleanupStack::PushL(img);img->DoSomethingDangerousL();CleanupStack::PopAndDestroy();    }identicalnew-Operator overloaded with ELeave:automated leave if there’s not enough memory!
Practice in a NutshellStrategiesexplained so far:Andreas Jakl, 200834CClass* CClass::NewL(TIntaInt, CBase& aObj){CClass* self = new (ELeave) CClass(aInt);CleanupStack::PushL(self);self->ConstructL(aObj);CleanupStack::Pop(self);returnself;}
Two-Phase ConstructionThe ultimate combination …Andreas Jakl, 200835
Resource Handling – Rule 3Andreas Jakl, 200836Neither a constructor nor a destructor may cause a leave!The destructor must not assume that the object was fully initialized.
Leaves in the ConstructorAndreas Jakl, 2008371. Call to constructorof CEngineApplicationCEngine* myEngine = new (ELeave) CEngine();……CEngineCEngine::CEngine() {iList = new (ELeave) CList();}CEngine::~CEngine() {deleteiList;}iListCEngine2. Leave – nomemory left for allocating iListHeap3. Because of the leavethere is no valid pointerto the partially constructedCEngine-object.4. Without a validpointer, the memoryalready allocatedfor CEngine is lost.?
Solution: Two-phase ConstructionAndreas Jakl, 200838ApplicationCEngine* myEngine = new (ELeave) CEngine();CleanupStack::Push(myEngine);myEngine->ConstructL();…// Note that the following line won’t be // reached in case of a leave!CleanupStack::PopAndDestroy(myEngine);CEngineCEngine::CEngine() {// 1. Phase}CEngine::ConstructL() {// 2. PhaseiList = new (ELeave) CList();}CEngine::~CEngine() {deleteiList;}iListCEngineHeapObject is fully allocated and on the cleanup stack  the destructor can be executed, the class is deleted by the cleanup stack  all memory is properly cleaned up in case of a leave!
Simplification: Two-phase ConstructionLess complicated creation of objects:Trailing C at the end of the function name: an object is left on the cleanup stack (as in NewLC())Andreas Jakl, 200839CEngineCEngine* CEngine::NewLC() {CEngine* self = new (ELeave) CEngine();    	// 1. PhaseCleanupStack::PushL(self);    self->ConstructL();    					// 2. Phasereturn self;}CEngine* CEngine::NewL() {CEngine* self = CEngine::NewLC();CleanupStack::Pop(self);return self;}Application – Local VariableCEngine* myEngine = CEngine::NewLC();…CleanupStack::PopAndDestroy(myEngine);orApplication– Instance VariableiMyEngine = CEngine::NewL();Destructor:delete iMyEngine;Application – Instance variableiMyEngine = CEngine::NewL();// Destructor:deleteiMyEngine;
Practice in a NutshellStrategiesexplained so far:Andreas Jakl, 200840CClass* CClass::NewL(TIntaInt, CBase& aObj){CClass* self = new (ELeave) CClass(aInt);CleanupStack::PushL(self);self->ConstructL(aObj);CleanupStack::Pop(self);returnself;}
DerivationNote:Some thoughts are necessary when deriving from a class that uses two-phase constructionSee the literature or Symbian Academy-slides for details!Andreas Jakl, 200841
Resource Handling – Rule 4Andreas Jakl, 200842If memory for a pointer (instance variable) is reallocated, set the old pointer to NULL beforehand.
NULLSituation (without NULL):AllocL() causes a leave, which propagates up …Instance of CElement is deletedDestructor of CElement is callediName still points to already deleted memoryDeleted 2x           PanicAndreas Jakl, 200843voidCEngine::DoStuffL(constTDesC& aName)    {CElement* element = CElement::NewLC();    TRAPD(err, element->SetNameL(aName));CleanupStack::PopAndDestroy(element);        }21voidCElement::SetNameL(constTDesC& aName)    {deleteiName;	       // Deletes object, does not change pointeriName = aName.AllocL();	// Re-Allocation    }voidCElement::~CElement()    {deleteiName;    }12iName = NULL;       // Deletes pointer on stackNote: delete does not delete a NULL pointer.
SummaryAndreas Jakl, 200844
SummaryCatch leaves (= exceptions) with TRAP(D)Use cleanup stack for local heap-based variablesDo not use the cleanup stack for instance variablesNo leaves in constructors or destructorsUse two-phase construction for objects with data on the heapSet a pointer to NULL before re-allocating memoryAndreas Jakl, 200845!
What’s wrong?Andreas Jakl, 200846CleanupStack::PushL(iList);
What’s wrong?Andreas Jakl, 200847CleanupStack::PushL(iList);Never push instance variables on the cleanup stack!Twice as safe isn’t safe at all…
What’s wrong?Andreas Jakl, 200848CEngine* engine = new (ELeave) CEngine();…CleanupStack::PopAndDestroy(engine)
What’s wrong?Andreas Jakl, 200849CEngine* engine = new (ELeave) CEngine();…CleanupStack::PopAndDestroy(engine)enginewasn‘t pushed on the cleanup stack!new (ELeave) is only responsible for leaving if memory allocation for the object fails. new (ELeave) has nothing to do with the cleanup stack.Solution: Either: add the object to the cleanup stack:CleanupStack::PushL(engine);Or: don’t use the cleanup stack for deleting – in case no leaving operation is called between creation and deletion of the engine object:delete engine;
What’s wrong?Andreas Jakl, 200850voidCGomokuViewGame::ChangeViewContextText(TIntaResourceId)	{RBufnewText(iEikonEnv->AllocReadResourceL(resourceId));newText.CleanupClosePushL ();MQikViewContext* viewContext = ViewContext ();	// Changing an alreadyexistingviewcontexttextviewContext->ChangeTextL (EGomokuViewContext, newText);CleanupStack::PopAndDestroy (1);	// newText	}
What’s wrong?Andreas Jakl, 200851void CGomokuViewGame::ChangeViewContextText(TInt aResourceId)	{	RBuf newText(iEikonEnv->AllocReadResourceL(resourceId));	newText.CleanupClosePushL ();	MQikViewContext* viewContext = ViewContext ();	// Changing an already existing view context text	viewContext->ChangeTextL (EGomokuViewContext, newText);	CleanupStack::PopAndDestroy (1);	// newText	}The trailing L of the function name is missing, as calls withinthe function can leave.Solution:void CGomokuViewGame::ChangeViewContextTextL(…)
Testing your CodeOn your way to perfectionAndreas Jakl, 200852
Macros for TestingWrap code you want to test within __UHEAP_MARK and __UHEAP_MARKEND:Andreas Jakl, 200853CClass* p1 = new (ELeave) CClass;__UHEAP_MARK;// Mark start of test-areaCClass* p2 = new (ELeave) CClass;CClass* p3 = new (ELeave) CClass;__UHEAP_CHECK(2);// 2 Objects (p2, p3) on the heap since the start-mark__UHEAP_CHECKALL(3);// In total 3 objects on the heapdelete p3;_UHEAP_MARKEND;// Result: p2 is still here – Memory Leak!// or:  __UHEAP_MARKENDC(1);// Expects one cell on the heap
Finding Memory LeaksEmulator checksheapautomaticallyifyouexittheprogram BEFORE closingtheemulatorwindow!Andreas Jakl, 200854Find it in theSymbian OS SDK doc:Symbian OS SDK v…  Symbian OS guide  Symbian OS reference  System panicreference
Memory InformationShow numberofallocatedcells:Ctrl+Alt+Shift+AAndreas Jakl, 200855
Allocation FailureIntentional failing of memory allocation:__UHEAP_SETFAIL(aType, aValue);EDeterministic: fail every nth requestERandom: fail randomly once within a specified range – always using the same seedETrueRandom: random seed taken from system timeAndreas Jakl, 200856__UHEAP_SETFAIL(RHeap::EDeterministic, 2);CObj* c1 = new (ELeave) CObj;		// will allocateCObj* c2 = new (ELeave) CObj;		// will failCObj* c3 = new (ELeave) CObj;		// will allocateCObj* c4 = new (ELeave) CObj;		// will fail__UHEAP_RESET;	// Deactivate
FAILNEXTFails thenextallocationrequestAndreas Jakl, 200857CObj* c1 = new (ELeave) CObj;		// will allocate__UHEAP_FAILNEXT(1);// failnextallocationCObj* c2 = new (ELeave) CObj;		// will fail
AllocationFailureIn theemulator, withoutwritingcode:Heap Failure ToolActivate:Ctrl+Alt+Shift+PDeactivate:Ctrl+Alt+Shift+QCan failheap, WindowServer-allocationsorfile-accessAndreas Jakl, 200858
… let’s move to the Challenges!Try it for your ownAndreas Jakl, 200859

More Related Content

PDF
Model-Based Testing: Why, What, How
Bob Binder
 
PDF
RMI Java Programming Lab Manual 2019
Gebreigziabher Ab
 
PPTX
Scheduling in symbian os
Hasib Shaikh
 
PPTX
Threads in JAVA
Haldia Institute of Technology
 
PPT
Thread model in java
AmbigaMurugesan
 
PPTX
Java socket programming
Mohammed Abdalla Youssif
 
PDF
Servlet and servlet life cycle
Dhruvin Nakrani
 
PPTX
Software Myths
Rajat Bajaj
 
Model-Based Testing: Why, What, How
Bob Binder
 
RMI Java Programming Lab Manual 2019
Gebreigziabher Ab
 
Scheduling in symbian os
Hasib Shaikh
 
Thread model in java
AmbigaMurugesan
 
Java socket programming
Mohammed Abdalla Youssif
 
Servlet and servlet life cycle
Dhruvin Nakrani
 
Software Myths
Rajat Bajaj
 

What's hot (20)

PPT
Chapter 7 - Deadlocks
Wayne Jones Jnr
 
PDF
tybsc it asp.net full unit 1,2,3,4,5,6 notes
WE-IT TUTORIALS
 
PPSX
Collections - Maps
Hitesh-Java
 
PPTX
Semaphore
Arafat Hossan
 
PPTX
Method overloading and constructor overloading in java
baabtra.com - No. 1 supplier of quality freshers
 
PPTX
Thread priorities
Then Murugeshwari
 
PPT
Selection of an appropriate project approach
tumetr1
 
PPTX
02 data types in java
রাকিন রাকিন
 
PDF
Lecture 7 Web Services JAX-WS & JAX-RS
Fahad Golra
 
PDF
Agile Methodology - Software Engineering
Purvik Rana
 
PPTX
Basic Software Effort Estimation
umair khan
 
PPT
14 file handling
APU
 
PDF
An Introduction to the Android Framework -- a core architecture view from app...
William Liang
 
PPT
Asp.net.
Naveen Sihag
 
PPTX
Distributed operating system
Prankit Mishra
 
PPTX
Process management
Birju Tank
 
DOCX
Critical section operating system
Muhammad Baqar Kazmi
 
PDF
Java Course 8: I/O, Files and Streams
Anton Keks
 
PPTX
android studio
Lahore Garrison University
 
PPTX
FreeSWITCH as a Kickass SBC
Moises Silva
 
Chapter 7 - Deadlocks
Wayne Jones Jnr
 
tybsc it asp.net full unit 1,2,3,4,5,6 notes
WE-IT TUTORIALS
 
Collections - Maps
Hitesh-Java
 
Semaphore
Arafat Hossan
 
Method overloading and constructor overloading in java
baabtra.com - No. 1 supplier of quality freshers
 
Thread priorities
Then Murugeshwari
 
Selection of an appropriate project approach
tumetr1
 
02 data types in java
রাকিন রাকিন
 
Lecture 7 Web Services JAX-WS & JAX-RS
Fahad Golra
 
Agile Methodology - Software Engineering
Purvik Rana
 
Basic Software Effort Estimation
umair khan
 
14 file handling
APU
 
An Introduction to the Android Framework -- a core architecture view from app...
William Liang
 
Asp.net.
Naveen Sihag
 
Distributed operating system
Prankit Mishra
 
Process management
Birju Tank
 
Critical section operating system
Muhammad Baqar Kazmi
 
Java Course 8: I/O, Files and Streams
Anton Keks
 
FreeSWITCH as a Kickass SBC
Moises Silva
 
Ad

Viewers also liked (20)

ODP
Symbian OS
guest7e14b6a
 
PPT
Symbian mobile operating system ppt
Devesh Singh
 
PPT
Symbian os presentation
Priya Pandharbale
 
PPTX
Symbian Operating system
Pravin Shinde
 
PPTX
Symbian os
Amit Tyagi
 
PPT
Symbian Os Introduction
Deepak Rathi
 
PPTX
Symbian OS
Adit Pathak
 
PPT
Symbian OS
NIKHIL NAIR
 
PPT
Part 2
jkporter1
 
PPTX
Symbionic os
bhavithd
 
PPTX
Communication in Symbian OS
quasar_knowledge
 
PPTX
Symbian OS - Communication And Messaging
Andreas Jakl
 
PPTX
Symbian OS Overview
Andreas Jakl
 
PDF
Chrome OS Observation
Champ Yen
 
PPTX
Google chrome os
devaj kumar
 
PDF
Chrome OS: The Stateless Operating System
Chatchai Wangwiwattana
 
PPTX
Google chrome os
akoyena
 
PPTX
Google chrome
Nayana_Bingi
 
PDF
Google Chrome OS
Er. Saurabh Singh
 
PPT
Chrome os
vishal jadav
 
Symbian OS
guest7e14b6a
 
Symbian mobile operating system ppt
Devesh Singh
 
Symbian os presentation
Priya Pandharbale
 
Symbian Operating system
Pravin Shinde
 
Symbian os
Amit Tyagi
 
Symbian Os Introduction
Deepak Rathi
 
Symbian OS
Adit Pathak
 
Symbian OS
NIKHIL NAIR
 
Part 2
jkporter1
 
Symbionic os
bhavithd
 
Communication in Symbian OS
quasar_knowledge
 
Symbian OS - Communication And Messaging
Andreas Jakl
 
Symbian OS Overview
Andreas Jakl
 
Chrome OS Observation
Champ Yen
 
Google chrome os
devaj kumar
 
Chrome OS: The Stateless Operating System
Chatchai Wangwiwattana
 
Google chrome os
akoyena
 
Google chrome
Nayana_Bingi
 
Google Chrome OS
Er. Saurabh Singh
 
Chrome os
vishal jadav
 
Ad

Similar to Symbian OS - Memory Management (20)

PDF
A exception ekon16
Max Kleiner
 
PDF
RAII and ScopeGuard
Andrey Dankevich
 
PDF
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
PVS-Studio
 
PDF
Discussing Errors in Unity3D's Open-Source Components
PVS-Studio
 
PDF
How to make fewer errors at the stage of code writing. Part N4.
PVS-Studio
 
PPT
Handling Exceptions In C & C++ [Part B] Ver 2
ppd1961
 
PDF
Grounded Pointers
Andrey Karpov
 
PDF
Can We Trust the Libraries We Use?
Andrey Karpov
 
PDF
How to make fewer errors at the stage of code writing. Part N1
Andrey Karpov
 
PDF
How to make fewer errors at the stage of code writing. Part N1.
PVS-Studio
 
PPTX
What has to be paid attention when reviewing code of the library you develop
Andrey Karpov
 
PDF
The Little Unicorn That Could
PVS-Studio
 
PDF
100 bugs in Open Source C/C++ projects
Andrey Karpov
 
PDF
Exception+Logging=Diagnostics 2011
Paulo Gaspar
 
PDF
CppCat Static Analyzer Review
Andrey Karpov
 
PPTX
Case Study of the Unexplained
shannomc
 
PDF
Miranda NG Project to Get the "Wild Pointers" Award (Part 1)
Andrey Karpov
 
PDF
The Unicorn's Travel to the Microcosm
Andrey Karpov
 
PDF
Memory Safety with Delphi - Jim McKeeth - Webinar June 2024
Jim McKeeth
 
PPT
CLR Exception Handing And Memory Management
Shiny Zhu
 
A exception ekon16
Max Kleiner
 
RAII and ScopeGuard
Andrey Dankevich
 
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
PVS-Studio
 
Discussing Errors in Unity3D's Open-Source Components
PVS-Studio
 
How to make fewer errors at the stage of code writing. Part N4.
PVS-Studio
 
Handling Exceptions In C & C++ [Part B] Ver 2
ppd1961
 
Grounded Pointers
Andrey Karpov
 
Can We Trust the Libraries We Use?
Andrey Karpov
 
How to make fewer errors at the stage of code writing. Part N1
Andrey Karpov
 
How to make fewer errors at the stage of code writing. Part N1.
PVS-Studio
 
What has to be paid attention when reviewing code of the library you develop
Andrey Karpov
 
The Little Unicorn That Could
PVS-Studio
 
100 bugs in Open Source C/C++ projects
Andrey Karpov
 
Exception+Logging=Diagnostics 2011
Paulo Gaspar
 
CppCat Static Analyzer Review
Andrey Karpov
 
Case Study of the Unexplained
shannomc
 
Miranda NG Project to Get the "Wild Pointers" Award (Part 1)
Andrey Karpov
 
The Unicorn's Travel to the Microcosm
Andrey Karpov
 
Memory Safety with Delphi - Jim McKeeth - Webinar June 2024
Jim McKeeth
 
CLR Exception Handing And Memory Management
Shiny Zhu
 

More from Andreas Jakl (20)

PDF
Create Engaging Healthcare Experiences with Augmented Reality
Andreas Jakl
 
PDF
AR / VR Interaction Development with Unity
Andreas Jakl
 
PDF
Android Development with Kotlin, Part 3 - Code and App Management
Andreas Jakl
 
PDF
Android Development with Kotlin, Part 2 - Internet Services and JSON
Andreas Jakl
 
PDF
Android Development with Kotlin, Part 1 - Introduction
Andreas Jakl
 
PDF
Android and NFC / NDEF (with Kotlin)
Andreas Jakl
 
PDF
Basics of Web Technologies
Andreas Jakl
 
PDF
Bluetooth Beacons - Bluetooth 5, iBeacon, Eddystone, Arduino, Windows 10 & More
Andreas Jakl
 
PDF
Which new scenarios are enabled by Windows 10 for NFC, Bluetooth LE & Beacons?
Andreas Jakl
 
PDF
Mobile Test Automation
Andreas Jakl
 
PDF
Qt App Development - Cross-Platform Development for Android, iOS, Windows Pho...
Andreas Jakl
 
PDF
WinJS, Apache Cordova & NFC - HTML5 apps for Android and Windows Phone
Andreas Jakl
 
PDF
Nokia New Asha Platform Developer Training
Andreas Jakl
 
PDF
Windows Phone 8 NFC Quickstart
Andreas Jakl
 
PDF
Windows (Phone) 8 NFC App Scenarios
Andreas Jakl
 
PDF
Windows 8 Platform NFC Development
Andreas Jakl
 
PDF
NFC Development with Qt - v2.2.0 (5. November 2012)
Andreas Jakl
 
PDF
06 - Qt Communication
Andreas Jakl
 
PDF
05 - Qt External Interaction and Graphics
Andreas Jakl
 
PDF
04 - Qt Data
Andreas Jakl
 
Create Engaging Healthcare Experiences with Augmented Reality
Andreas Jakl
 
AR / VR Interaction Development with Unity
Andreas Jakl
 
Android Development with Kotlin, Part 3 - Code and App Management
Andreas Jakl
 
Android Development with Kotlin, Part 2 - Internet Services and JSON
Andreas Jakl
 
Android Development with Kotlin, Part 1 - Introduction
Andreas Jakl
 
Android and NFC / NDEF (with Kotlin)
Andreas Jakl
 
Basics of Web Technologies
Andreas Jakl
 
Bluetooth Beacons - Bluetooth 5, iBeacon, Eddystone, Arduino, Windows 10 & More
Andreas Jakl
 
Which new scenarios are enabled by Windows 10 for NFC, Bluetooth LE & Beacons?
Andreas Jakl
 
Mobile Test Automation
Andreas Jakl
 
Qt App Development - Cross-Platform Development for Android, iOS, Windows Pho...
Andreas Jakl
 
WinJS, Apache Cordova & NFC - HTML5 apps for Android and Windows Phone
Andreas Jakl
 
Nokia New Asha Platform Developer Training
Andreas Jakl
 
Windows Phone 8 NFC Quickstart
Andreas Jakl
 
Windows (Phone) 8 NFC App Scenarios
Andreas Jakl
 
Windows 8 Platform NFC Development
Andreas Jakl
 
NFC Development with Qt - v2.2.0 (5. November 2012)
Andreas Jakl
 
06 - Qt Communication
Andreas Jakl
 
05 - Qt External Interaction and Graphics
Andreas Jakl
 
04 - Qt Data
Andreas Jakl
 

Recently uploaded (20)

PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PDF
Doc9.....................................
SofiaCollazos
 
PDF
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
PPTX
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
PDF
Software Development Methodologies in 2025
KodekX
 
PDF
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
PDF
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
PPTX
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
PPTX
Coupa-Overview _Assumptions presentation
annapureddyn
 
PDF
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
PDF
Architecture of the Future (09152021)
EdwardMeyman
 
PDF
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
PDF
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
PDF
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
PPTX
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
PDF
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
Doc9.....................................
SofiaCollazos
 
CIFDAQ's Market Wrap : Bears Back in Control?
CIFDAQ
 
What-is-the-World-Wide-Web -- Introduction
tonifi9488
 
Software Development Methodologies in 2025
KodekX
 
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
 
Applied-Statistics-Mastering-Data-Driven-Decisions.pptx
parmaryashparmaryash
 
Coupa-Overview _Assumptions presentation
annapureddyn
 
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
Architecture of the Future (09152021)
EdwardMeyman
 
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
 
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
Oracle AI Vector Search- Getting Started and what's new in 2025- AIOUG Yatra ...
Sandesh Rao
 
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
NewMind AI Weekly Chronicles - July'25 - Week IV
NewMind AI
 

Symbian OS - Memory Management

  • 1. Symbian OSMemory Managementv2.0a – 21 May 20081Andreas Jakl, 2008
  • 2. DisclaimerThese slides are provided free of charge at http://www.symbianresources.com and are used during Symbian OS courses at the University of Applied Sciences in Hagenberg, Austria ( http://www.fh-hagenberg.at/ )Respecting the copyright laws, you are allowed to use them:for your own, personal, non-commercial usein the academic environmentIn all other cases (e.g. for commercial training), please contact [email protected] correctness of the contents of these materials cannot be guaranteed. Andreas Jakl is not liable for incorrect information or damage that may arise from using the materials.Parts of these materials are based on information from Symbian Press-books published by John Wiley & Sons, Ltd. This document contains copyright materials which are proprietary to Symbian, UIQ, Nokia and SonyEricsson. “S60™” is a trademark of Nokia. “UIQ™” is a trademark of UIQ Technology. Pictures of mobile phones or applications are copyright their respective manufacturers / developers. “Symbian ™”, “Symbian OS ™” and all other Symbian-based marks and logos are trademarks of Symbian Software Limited and are used under license. © Symbian Software Limited 2006. Andreas Jakl, 20082
  • 3. ScheduleLeaves, Panics and TRAP(D)CleanupstackObjectconstructionusingELeaveTwo-phaseconstructionDebugging toolsAndreas Jakl, 20083
  • 4. Leaves & PanicsHandling problemsAndreas Jakl, 20084
  • 5. Exceptions – JavaTry & Catch for handling exceptionsFunctions can throw “Exceptions”Andreas Jakl, 20085Integer Class…static intparseIntthrowsNumberFormatException {…}…Calling functionTry {int x = Integer.parseInt(“1234”);} catch (NumberFormatException e) {System.out.println(“Unable to convert this String to a number.”);}
  • 6. Leave – SymbianTRAP(D) catches exceptions (“Leave”)Functions send out leaveFunction name marked by an L-suffixAndreas Jakl, 20086The TRAP(D) macros are defined in e32cmn.hMain-FunctionTRAPD(err, DoExampleL());if (err) { console->Printf(KTxtFailed, err); }DoExampleL()-FunctionvoidDoExampleL() {RFsfsSession; // Connect to the file serverUser::LeaveIfError(fsSession.Connect()); // …fsSession.Close(); }TRAPD-Makro declares err as TInt and = KErrNoneLeaves if the Connect() function does not return KErrNone
  • 7. Central ExceptionHandlingAndreas Jakl, 20087New (ELeave) … … NewL() … … User::Leave() …… ConstructL() …F6L()F7L()F8L()F9L()F5L()F5L() … … F6L() ….… F8L() ….F3L()F4L()F0L()F2L()… F3L() …F4L() …F1L()TRAPD(err, F2L());if(err) …
  • 8. Handling LeavesTry to implement central leave-handlingIf leave not handled by your code  error-message shown by the UI-framework!Therefore: Only handle leaves yourself if they influence your applicationAndreas Jakl, 20088
  • 9. When can a function leave?Caused by your own code:User::Leave(), User::LeaveIfError(), User::LeaveNoMemory() or User::LeaveIfNull()Failed object-constructionwhen using the “new (ELeave)”-operatorCalling a function that potentially causes a leavee.g. x->DoSomethingL()Andreas Jakl, 20089
  • 10. Details: Causing a LeaveUser::Leave(TIntaReason)Error code (aReason) = value that will be received by TRAPCauses leave in any caseUser::LeaveIfError(TIntaReason)Causes leave if parameter is negative, e.g.:TIntfoundAt = iElementArray.Find(example, aRelation);User::LeaveIfError(foundAt); // Leaves if foundAt == KErrNotFound (-1)User::LeaveNoMemory()Is the same as: User:Leave(KErrNoMem);User::LeaveIfNull(TAny* aPtr)Andreas Jakl, 200810
  • 11. TRAP / TRAPDTwo trap harness macros:TRAP: declares the variable in which the leave code is returnedTRAPD: declare a TIntvariable yourselfIf a leave occurs inside MayLeaveL(), which is executed inside the harness, the program code will return immediately to the TRAP harness macroThe variable result will contain the error code associated with the leave or will be KErrNoneif no leave occuredAndreas Jakl, 200811TRAPD(result, MayLeaveL());if (KErrNone!=result)...is equivalent to:TIntresult;TRAP(result, MayLeaveL());if (KErrNone!=result)...
  • 12. TipsAndreas Jakl, 200812XvoidInsertData() {TInt err; TRAP(err, iData->InsertL(23));if (err) { ... } TRAP(err, iData->InsertL(24));if (err) { ... } }TRAPs are expensiveDon’t use several TRAPs right after each otherInstead:Make the function leave (append an L to the function name)Handle all errors in a single TRAP-call one level above!In UI apps, many leaves don’t have to be handled by you  they can go up to the topmost level (= Active Scheduler)prefervoidHandleCommand() { TRAPD(err, InsertDataL());if (err) { ... } }voidInsertDataL() {iData->InsertL(23));iData->InsertL(24)); }
  • 13. Panics... cannot be caught and handled!Terminates thread (= usually the whole application)Use them for checking code logic onlyCan also be sent out by the system for critical errorsIf a panic happens:Make sure you fix it, as you can’t handle it!Andreas Jakl, 200813// Stray signal detected!_LIT(KMsgStraySignal, "Stray signal\n");User::Panic(KMsgStraySignal, 1); // Panic with code 1
  • 14. Resource HandlingStack, Heap and the Cleanup StackAndreas Jakl, 200814
  • 15. Practice in a NutshellAll strategiesarepresent in thisfunction:Andreas Jakl, 200815CClass* CClass::NewL(TIntaInt, CBase& aObj){CClass* self = new (ELeave) CClass(aInt);CleanupStack::PushL(self);self->ConstructL(aObj);CleanupStack::Pop(self);returnself;}
  • 16. Recap: StackAndreas Jakl, 200816// Stack (1)voidCTest::F1(){TInt x = 0;TInt y = 1;for(x = 0; x < 10; x++) y++ y = y + F2(); // Stack (4)}// Stack (5)TIntCTest::F2(){TInt a = 2;TInt b = 1;return a + b; // Stack (3)}Stack (2)Stack(5)Stack(1)TInt yTInt xF1Stack(2)TInt yTInt xF1Stack(4)TInt bTInt aF2TInt yTInt xF1Stack(3)
  • 17. Recap: HeapUse for:Objects that need a lot of memory ( stack-size is limited!)Required amount of memoryonlyknown at runtimeScope of heap-objects is not limited to a functionUse pointers to pass to other functions/objectsAndreas Jakl, 200817
  • 18. MotivationSymbian OS designed to run for many years No opportunity to reclaim leaked memory through regular restarts!Small memory leaks accumulate over timeWe only have a small memory to start withTherefore: Simply write perfect, leak-free code!Andreas Jakl, 200818
  • 19. Motivation – How?By keeping track of all allocated objects!By making sure:All heap-objects are pointed to by at least one pointer, all the time – even in the constructor of an object!Free heap memory as soon as possible after use.Andreas Jakl, 200819
  • 21. Resource Handling – Rule 1Andreas Jakl, 200821Every local pointer to an instance of a heap-based object also has to be pushed on the cleanup stack, if there‘s the risk that the pointer gets lost because of a leave.
  • 22. Cleanup StackSituation: function creates local heap-objectBefore code gets to the delete-statement: errorFunction is left (Leave)Pointer-address on the stack is freedObject itself is orphaned memory leak!Andreas Jakl, 200822voidCImage::DoSomethingDangerousL() { User::Leave(KErrNotFound); }CImagevoidCMyObj::DoSomethingL(){}CImage* img = new (ELeave) CImage();img->DoSomethingDangerousL();deleteimg;img = pointer on the stack to an instance on the heap
  • 23. Cleanup StackMemory situation if a leave occurs:Andreas Jakl, 200823!XXimgHeapStackObject stays on the heap;Pointer to delete the instance is lostmemory leak
  • 24. Cleanup StackSolution: Cleanup StackAndreas Jakl, 200824void CMyObj::DoSomethingL(){CImage* img = new (ELeave) CImage();CleanupStack::PushL(img);img->DoSomethingDangerousL();CleanupStack::PopAndDestroy();}imgCleanupStackXXimgHeapStackWhen no leave occurs: object still has to be deleted by you + removed from the cleanup stack!Cleanup stack saves a second pointerto the object on the heap.
  • 25. AdvancedCleanupAndreas Jakl, 200825RFileForresourcesthathavetobeclosed / freed(e.g.: files, sockets, …)Close(): CleanupClosePushL(T&)Release(): CleanupReleasePushL(T&)Destructor: CleanupDeletePushL(T*)Close()TCleanupOperationTAny* aPtr…TCleanupItemCleanupStack
  • 26. AdvancedCleanup – ExampleAndreas Jakl, 200826voidCMyClass::TransferDataL() {RSocketServsocketServer; // Connect to SocketServer User::LeaveIfError( socketServer.Connect() ); // Make sure Close() is called at the endCleanupClosePushL( socketServer );// …CleanupStack::PopAndDestroy(); // socketServer }
  • 27. Cleanup Stack and Ownership TransferIt should never be possible for an object to be deleted more than once!Andreas Jakl, 200827voidTransferOwnershipExampleL() { // The stack variable ptr points to memory allocated on the heapCItem* ptr = new (ELeave) CItem(); // The following function may leave -> place the pointer on the // cleanup stack, so that the heap memory is freed in case // AppendL() leaves.CleanupStack::PushL(ptr); // iItemPtrArray takes ownership of the CItem object. // This could fail, as it needs to allocate a new slot to store the pointer, // therefore the object was placed on the cleanup stack in advanceiItemPtrArray->AppendL(ptr); // iItemArray now owns the heap object, so ptr may be safely popped off the stack. // It shouldn’t be destroyed, as this would make the item in iItemPtrArray invalid!CleanupStack::Pop(ptr); }
  • 28. Practice in a NutshellStrategiesexplaineduptonow:Andreas Jakl, 200828CClass* CClass::NewL(TIntaInt, CBase& aObj){CClass* self = new (ELeave) CClass(aInt);CleanupStack::PushL(self);self->ConstructL(aObj);CleanupStack::Pop(self);returnself;}
  • 29. Resource Handling – Rule 2Andreas Jakl, 200829Never push instance variables on the cleanup stack!The owning class is also on the cleanup stack somewhere (at least indirectly). This would lead to a double deletion of the object pointed to by the instance variable  Panic!
  • 30. Coding Error ExampleAndreas Jakl, 200830class CSimple : CBase { public: ~CSimple(); void MayLeaveFuncL();private: void PrivateMayLeaveL();CItem* iItem; };CSimple* simple = new (ELeave) CSimple();CleanupStack::PushL(simple);1. CSimple is created and pushed onto the cleanup stack as the next function may leaveTRAPD(res,simple->MayLeaveFuncL());...2. A leaving method is called on simplevoid CSimple::MayLeaveFuncL() {iItem= new (ELeave) CItem();CleanupStack::PushL(iItem);PrivateMayLeaveL();CleanupStack::Pop(iItem); }3. The member variable is pushed onto the clean up stack (oops!)5. The TRAP does the right thing and clears the cleanup stack; i.e. CSimple::iItem is deleted 4. What happens if a leaves occurs? ...6. The code logic completes with the popping and deleting of the simple object.CleanupStack::PopAndDestroy(simple);CSimple::~CSimple { delete iItem; }BUT this calls the CSimple destructor, which deletes the iItem which has already been deleted by the TRAP 7. PANIC!Example taken from theSymbian Academy slides
  • 32. New Objectsnew-operator allocates memory and runs constructorReturns null-pointer if object creation fails(e.g. not enough memory) manual test required to see if it was successful – no automated leave!Andreas Jakl, 200832void CMyObj::DoSomethingL() {CImage* img = newCImage(); if (img) {CleanupStack::PushL(img);img->DoSomethingDangerousL();CleanupStack::PopAndDestroy();} else { User::LeaveNoMemory(); } }
  • 33. New Objects – ELeaveAndreas Jakl, 200833void CMyObj::DoSomethingL() {CImage* img = newCImage(); if (img) {CleanupStack::PushL(img);img->DoSomethingDangerousL();CleanupStack::PopAndDestroy();} else { User::LeaveNoMemory(); } }void CMyObj::DoSomethingL() {CImage* img = new (ELeave)CImage();CleanupStack::PushL(img);img->DoSomethingDangerousL();CleanupStack::PopAndDestroy(); }identicalnew-Operator overloaded with ELeave:automated leave if there’s not enough memory!
  • 34. Practice in a NutshellStrategiesexplained so far:Andreas Jakl, 200834CClass* CClass::NewL(TIntaInt, CBase& aObj){CClass* self = new (ELeave) CClass(aInt);CleanupStack::PushL(self);self->ConstructL(aObj);CleanupStack::Pop(self);returnself;}
  • 35. Two-Phase ConstructionThe ultimate combination …Andreas Jakl, 200835
  • 36. Resource Handling – Rule 3Andreas Jakl, 200836Neither a constructor nor a destructor may cause a leave!The destructor must not assume that the object was fully initialized.
  • 37. Leaves in the ConstructorAndreas Jakl, 2008371. Call to constructorof CEngineApplicationCEngine* myEngine = new (ELeave) CEngine();……CEngineCEngine::CEngine() {iList = new (ELeave) CList();}CEngine::~CEngine() {deleteiList;}iListCEngine2. Leave – nomemory left for allocating iListHeap3. Because of the leavethere is no valid pointerto the partially constructedCEngine-object.4. Without a validpointer, the memoryalready allocatedfor CEngine is lost.?
  • 38. Solution: Two-phase ConstructionAndreas Jakl, 200838ApplicationCEngine* myEngine = new (ELeave) CEngine();CleanupStack::Push(myEngine);myEngine->ConstructL();…// Note that the following line won’t be // reached in case of a leave!CleanupStack::PopAndDestroy(myEngine);CEngineCEngine::CEngine() {// 1. Phase}CEngine::ConstructL() {// 2. PhaseiList = new (ELeave) CList();}CEngine::~CEngine() {deleteiList;}iListCEngineHeapObject is fully allocated and on the cleanup stack  the destructor can be executed, the class is deleted by the cleanup stack  all memory is properly cleaned up in case of a leave!
  • 39. Simplification: Two-phase ConstructionLess complicated creation of objects:Trailing C at the end of the function name: an object is left on the cleanup stack (as in NewLC())Andreas Jakl, 200839CEngineCEngine* CEngine::NewLC() {CEngine* self = new (ELeave) CEngine(); // 1. PhaseCleanupStack::PushL(self); self->ConstructL(); // 2. Phasereturn self;}CEngine* CEngine::NewL() {CEngine* self = CEngine::NewLC();CleanupStack::Pop(self);return self;}Application – Local VariableCEngine* myEngine = CEngine::NewLC();…CleanupStack::PopAndDestroy(myEngine);orApplication– Instance VariableiMyEngine = CEngine::NewL();Destructor:delete iMyEngine;Application – Instance variableiMyEngine = CEngine::NewL();// Destructor:deleteiMyEngine;
  • 40. Practice in a NutshellStrategiesexplained so far:Andreas Jakl, 200840CClass* CClass::NewL(TIntaInt, CBase& aObj){CClass* self = new (ELeave) CClass(aInt);CleanupStack::PushL(self);self->ConstructL(aObj);CleanupStack::Pop(self);returnself;}
  • 41. DerivationNote:Some thoughts are necessary when deriving from a class that uses two-phase constructionSee the literature or Symbian Academy-slides for details!Andreas Jakl, 200841
  • 42. Resource Handling – Rule 4Andreas Jakl, 200842If memory for a pointer (instance variable) is reallocated, set the old pointer to NULL beforehand.
  • 43. NULLSituation (without NULL):AllocL() causes a leave, which propagates up …Instance of CElement is deletedDestructor of CElement is callediName still points to already deleted memoryDeleted 2x  PanicAndreas Jakl, 200843voidCEngine::DoStuffL(constTDesC& aName) {CElement* element = CElement::NewLC(); TRAPD(err, element->SetNameL(aName));CleanupStack::PopAndDestroy(element); }21voidCElement::SetNameL(constTDesC& aName) {deleteiName; // Deletes object, does not change pointeriName = aName.AllocL(); // Re-Allocation }voidCElement::~CElement() {deleteiName; }12iName = NULL; // Deletes pointer on stackNote: delete does not delete a NULL pointer.
  • 45. SummaryCatch leaves (= exceptions) with TRAP(D)Use cleanup stack for local heap-based variablesDo not use the cleanup stack for instance variablesNo leaves in constructors or destructorsUse two-phase construction for objects with data on the heapSet a pointer to NULL before re-allocating memoryAndreas Jakl, 200845!
  • 46. What’s wrong?Andreas Jakl, 200846CleanupStack::PushL(iList);
  • 47. What’s wrong?Andreas Jakl, 200847CleanupStack::PushL(iList);Never push instance variables on the cleanup stack!Twice as safe isn’t safe at all…
  • 48. What’s wrong?Andreas Jakl, 200848CEngine* engine = new (ELeave) CEngine();…CleanupStack::PopAndDestroy(engine)
  • 49. What’s wrong?Andreas Jakl, 200849CEngine* engine = new (ELeave) CEngine();…CleanupStack::PopAndDestroy(engine)enginewasn‘t pushed on the cleanup stack!new (ELeave) is only responsible for leaving if memory allocation for the object fails. new (ELeave) has nothing to do with the cleanup stack.Solution: Either: add the object to the cleanup stack:CleanupStack::PushL(engine);Or: don’t use the cleanup stack for deleting – in case no leaving operation is called between creation and deletion of the engine object:delete engine;
  • 50. What’s wrong?Andreas Jakl, 200850voidCGomokuViewGame::ChangeViewContextText(TIntaResourceId) {RBufnewText(iEikonEnv->AllocReadResourceL(resourceId));newText.CleanupClosePushL ();MQikViewContext* viewContext = ViewContext (); // Changing an alreadyexistingviewcontexttextviewContext->ChangeTextL (EGomokuViewContext, newText);CleanupStack::PopAndDestroy (1); // newText }
  • 51. What’s wrong?Andreas Jakl, 200851void CGomokuViewGame::ChangeViewContextText(TInt aResourceId) { RBuf newText(iEikonEnv->AllocReadResourceL(resourceId)); newText.CleanupClosePushL (); MQikViewContext* viewContext = ViewContext (); // Changing an already existing view context text viewContext->ChangeTextL (EGomokuViewContext, newText); CleanupStack::PopAndDestroy (1); // newText }The trailing L of the function name is missing, as calls withinthe function can leave.Solution:void CGomokuViewGame::ChangeViewContextTextL(…)
  • 52. Testing your CodeOn your way to perfectionAndreas Jakl, 200852
  • 53. Macros for TestingWrap code you want to test within __UHEAP_MARK and __UHEAP_MARKEND:Andreas Jakl, 200853CClass* p1 = new (ELeave) CClass;__UHEAP_MARK;// Mark start of test-areaCClass* p2 = new (ELeave) CClass;CClass* p3 = new (ELeave) CClass;__UHEAP_CHECK(2);// 2 Objects (p2, p3) on the heap since the start-mark__UHEAP_CHECKALL(3);// In total 3 objects on the heapdelete p3;_UHEAP_MARKEND;// Result: p2 is still here – Memory Leak!// or: __UHEAP_MARKENDC(1);// Expects one cell on the heap
  • 54. Finding Memory LeaksEmulator checksheapautomaticallyifyouexittheprogram BEFORE closingtheemulatorwindow!Andreas Jakl, 200854Find it in theSymbian OS SDK doc:Symbian OS SDK v…  Symbian OS guide  Symbian OS reference  System panicreference
  • 56. Allocation FailureIntentional failing of memory allocation:__UHEAP_SETFAIL(aType, aValue);EDeterministic: fail every nth requestERandom: fail randomly once within a specified range – always using the same seedETrueRandom: random seed taken from system timeAndreas Jakl, 200856__UHEAP_SETFAIL(RHeap::EDeterministic, 2);CObj* c1 = new (ELeave) CObj; // will allocateCObj* c2 = new (ELeave) CObj; // will failCObj* c3 = new (ELeave) CObj; // will allocateCObj* c4 = new (ELeave) CObj; // will fail__UHEAP_RESET; // Deactivate
  • 57. FAILNEXTFails thenextallocationrequestAndreas Jakl, 200857CObj* c1 = new (ELeave) CObj; // will allocate__UHEAP_FAILNEXT(1);// failnextallocationCObj* c2 = new (ELeave) CObj; // will fail
  • 58. AllocationFailureIn theemulator, withoutwritingcode:Heap Failure ToolActivate:Ctrl+Alt+Shift+PDeactivate:Ctrl+Alt+Shift+QCan failheap, WindowServer-allocationsorfile-accessAndreas Jakl, 200858
  • 59. … let’s move to the Challenges!Try it for your ownAndreas Jakl, 200859