Memory Management in Bada/C++
I’ve been getting a hard time knowing the right moment when you must delete, or in other words, deallocate a pointer. Thats why I could never get used to using C++ even if I probably used it for two times. Now that in Bada Development, I’m back programming on C++. These are what I had extracted from the Internet to be a reminder or a checklist whether or not I’m doing things right:
(I am still unsure of some of them since I still have to test them myself)
- Standard Deallocation -
// Creation int *x = new int; // Deallocation delete x;
- Array Deallocation -
// Creation char *str = new char[30]; // Deallocation delete [] str;
- 2D Array Deallocation -
// Creation
byte **array = new byte*[3];
for(int i=0; i < 3; i++) {
array[i] = new byte[i+1];
}
// Deallocation
for(i=0; i < 3; i++) {
delete [] array[i];
}
delete [] array;
C++ Reminders
- Before reusing a pointer, deallocate the pointer first
- Before assigning a value to a pointer, deallocate first if pointer is alreader pointing somewhere
- If you declare a pointer within a function, make sure you delete it before the function ends
- Destructor of classes must be virtual
- Never return an address of a local pointer variable from a function, either return a real value or initialize the value into the pointer.
Bada Reminders
- Use Resource Monitor View (Debug on Simulator) to track memory leaks. — Alternatively use Osp::System::RuntimeInfo
- Methods that end with ‘N’ like pClass->GetCanvasN() return pointers that must be deleted after use.
- Deallocate all objects constructed except UI Controls added to a UI Container with AddControl(). On the other hand, delete all UI Controls which do not get added to a UI Container: MessageBox, Popup, ContextMenu, OptionMenu
- Deallocate Variables in Forms, do it two times, OnTerminating and the destructor. But after deleting in OnTerminating, assign zero(0) the pointer.
- To deallocate a UI Control, use RemoveControl() or RemoveAllControls()
- To deallocate other types, check API for methods with ‘Remove’ as prefix
- Delete pointers as soon as they are not used.
- Deallocate controls that are not seen, and just add them to the container when you need to see them again