malloc碎片優(yōu)化管理機(jī)制(附代碼)
1.mm_management_init()初始化函數(shù)
void mm_management_init(unsigned int free_memory_start, unsigned int free_memory_end)
傳入?yún)?shù)free_memory_start是內(nèi)存初始化之后,剩余可申請(qǐng)的首地址,該地址,一般會(huì)傳入到main函數(shù),如果main()函數(shù)沒有傳入該參數(shù)的話,可以在內(nèi)存初始化之后,自己malloc(4)申請(qǐng)一下,把返回的地址作為mm_management_init()函數(shù)的第一個(gè)參數(shù);
2.mm_management_malloc()申請(qǐng)函數(shù)
unsigned int mm_management_malloc(unsigned int size)
申請(qǐng)內(nèi)存的時(shí)候,先判斷size大小,如果大小可以在內(nèi)存管理機(jī)制中找到,則直接返回提前申請(qǐng)地址,如果大小不滿足,或者小內(nèi)存已被申請(qǐng)完,則用malloc重新申請(qǐng)
3.mm_management_free()
void mm_management_free(void *mm_ptr)
與mm_management_malloc()相反,先檢查所有小內(nèi)存鏈表是都有該地址,有的話就把該地址內(nèi)存清0,并把標(biāo)記設(shè)為MM_STATUS_FREE;如果是用malloc申請(qǐng)的,當(dāng)時(shí)是free()釋放掉;
#include
#include
#define C_MM_16BYTE_NUM (32)
#define C_MM_64BYTE_NUM (16)
#define C_MM_256BYTE_NUM (12)
#define C_MM_512BYTE_NUM (12)
#define C_MM_1024BYTE_NUM (18)
#define C_MM_4096BYTE_NUM (30)
#define C_MM_16BYTE (16)
#define C_MM_64BYTE (64)
#define C_MM_256BYTE (256)
#define C_MM_512BYTE (512)
#define C_MM_1024BYTE (1024)
#define C_MM_4096BYTE (4096)
#define C_MM_MAX_SIZE C_MM_4096BYTE //碎片管理最大的碎片大小
#define MM_STATUS_FREE (0) //0:表示內(nèi)存空閑
#define MM_STATUS_BUSY (1) //1:表示內(nèi)存已被申請(qǐng)
#define MM_STATUS_OK (0)
#define MM_STATUS_FAIL (1)
typedef struct mm_node_struct {
unsigned int *mm_node; //存放內(nèi)存節(jié)點(diǎn)指針
unsigned short iflag; //指針是否空閑
struct P_MM_Node_STRUCT *next; //指向下一個(gè)內(nèi)存節(jié)點(diǎn)指針
} MM_Node_STRUCT, *P_MM_Node_STRUCT;
typedef struct mm_sdram_struct {
unsigned int count;
P_MM_Node_STRUCT *next;
} MM_SDRAM_STRUCT, *P_MM_SDRAM_STRUCT;
static MM_SDRAM_STRUCT mm_fix_16_head;
static MM_SDRAM_STRUCT mm_fix_64_head;
static MM_SDRAM_STRUCT mm_fix_256_head;
static MM_SDRAM_STRUCT mm_fix_512_head;
static MM_SDRAM_STRUCT mm_fix_1024_head;
static MM_SDRAM_STRUCT mm_fix_4096_head;
static P_MM_SDRAM_STRUCT pmm_fix_16_head =