Memory manager
|
1. malloc and free are not in one function, or global variable memory manager
TXT_STATUS txt_bmk_destroy(PTXT_BMK_ITEM *ppTxt_bmk)
{
/*Must judge it null before free, because pointer can not free twice*/
if (*ppTxt_bmk != NULL)
{
txt_free(*ppTxt_bmk);
/*after free it you must set it to null to avoid wild pointer*/
*ppTxt_bmk = NULL;
}
return eTXT_SUCCESS;
}
TXT_STATUS txt_bmk_construct(PTXT_BMK_ITEM *ppTxt_bmk)
{
S32 i;
/*before you malloc, you must free previous data to avoid repeat malloc and memory leak*/
if (*ppTxt_bmk != NULL)
{
txt_bmk_destroy(ppTxt_bmk);
}
/*Malloc must use explicit type cast, and sizeof must be type not data*/
*ppTxt_bmk = (PTXT_BMK_ITEM)txt_malloc(TXT_BMK_MAX * sizeof(TXT_BMK_ITEM));
if ( *ppTxt_bmk == NULL)
{
/*some times malloc will be not execute successfully, return failed*/
return eTXT_NO_MEM;
}
/*after malloc successfully, initial it to zero to avoid pointer invalid use*/
for (i=0; i<TXT_BMK_MAX; i++)
{
memset(&(*ppTxt_bmk)[i], 0, sizeof(TXT_BMK_ITEM));
(*ppTxt_bmk)[i].status = BMK_NULL;
(*ppTxt_bmk)[i].line = TXT_BMK_INVALID_LINE;
}
return eTXT_SUCCESS;
}
2. use pointer correctly
/*after define it, must set it to null, avoid wild pointer*/
PTXT_BMK_ITEM g_pTxt_bmk = NULL;
/*Here must pass pointer & address to construct*/
txt_bmk_construct(&g_pTxt_bmk);
/*after the module execute, you must free the memory to avoid memory leak at the app end*/
txt_bmk_destroy(&g_pTxt_bmk);
3. some notes
3.1 when you complete a application, you should check memory carefully, before enter screen or a function, malloc a app struct, when the screen history is deleted, meant that you will not use it, you should free the app struct, and the same other malloc memory
eg. SetDelScrnIDCallbackHandler(SCR_ID_MYSETTING, (HistoryDelCBPtr) mmi_mysetting_del_scr_callback);
3.2 After complete a app moudle, check struct memory carefully
3.3 Some embedded platform notes
a) assure one application one entry and one exit function, so the memory can easily manager
b) one application has one global struct (cconv_context_struct *g_cconv_cntx = NULL;), once malloc and once free, not waste time, and also avoid too many global variable
c) because the stack is limits to 2k, so you can define the big array in the struct, it can be convenience
d) you can define the data which you must use in the application in the struct, so your application do not need to define other data, it is convenience
e) avoid some frequent occurring memory problem
f) you must add as prefix *g_snmp_cntx before your global variable, it mean a global module context pointer
g) you need add comment after each member of the struct, so the program can be easily understood by others
h) you must assign it to null in your definition (*g_cconv_cntx = NULL;), so to avoid other people use is before malloc it