/************************************************* * malloc & free in link node algorithm **************************************************/
#include <string.h> #include <malloc.h>
/************************************************* * struct definition **************************************************/
typedef struct _MNG_NODE { struct _MNG_NODE* next; unsigned int size; }MNG_NODE;
/************************************************* * macro declaration **************************************************/
#define MAX_SPEED_MALLOC 1 #define MIN_SIZE_MALLOC 0 #define MAX_SIZE_MALLOC 0
#define MEM_BUFFER_LENGTH (0x1 << 24)
/************************************************* * global variable declaration **************************************************/
static void* pGlbData; static MNG_NODE* pFreeList; static MNG_NODE* pAllocList;
/************************************************* * function declaration **************************************************/
MNG_NODE* find_previous_node_in_list(MNG_NODE* pNode, MNG_NODE* pList);
/************************************************* * function: add node into headlist **************************************************/
static void add_node_into_list_head(MNG_NODE* pNode, MNG_NODE** ppList) { pNode->next = *ppList; *ppList = pNode; }
#if MAX_SPEED_MALLOC /************************************************* * function: find best fit node in max_speed **************************************************/
static MNG_NODE* find_best_fit_node(unsigned int size) { MNG_NODE* pFind = pFreeList; MNG_NODE* pPre = pFind;
while(pFind && pFind->size < (size + sizeof(MNG_NODE))) { pPre = pFind; pFind = pFind->next; }
if(NULL == pFind) return NULL;
if(pFreeList == pFind) pFreeList = pFreeList->next; else pPre->next = pFind->next;
return pFind; } #endif
#if MIN_SIZE_MALLOC /************************************************* * function: find best fit node in min size **************************************************/
MNG_NODE* find_best_fit_node(unsigned int size) { MNG_NODE* pCur = pFreeList; MNG_NODE* pPre = pCur; MNG_NODE* pFind = NULL;
while(pCur) { if(pCur->size > (size + sizeof(MNG_NODE))) { if(NULL == pFind || pFind->size > pCur->size) { pFind = pCur; } }
pPre = pCur; pCur = pCur->next; }
if(NULL == pFind) return NULL;
pPre = find_previous_node_in_list(pFind, pFreeList); if(NULL == pPre) pFreeList = pFreeList->next; else pPre->next = pFind->next;
return pFind; } #endif |