malloc碎片优化管理机制(附代码)
扫描二维码
随时随地手机看文章
1.mm_management_init()初始化函数
void mm_management_init(unsigned int free_memory_start, unsigned int free_memory_end)
传入参数free_memory_start是内存初始化之后,剩余可申请的首地址,该地址,一般会传入到main函数,如果main()函数没有传入该参数的话,可以在内存初始化之后,自己malloc(4)申请一下,把返回的地址作为mm_management_init()函数的第一个参数;
2.mm_management_malloc()申请函数
unsigned int mm_management_malloc(unsigned int size)
申请内存的时候,先判断size大小,如果大小可以在内存管理机制中找到,则直接返回提前申请地址,如果大小不满足,或者小内存已被申请完,则用malloc重新申请
3.mm_management_free()
void mm_management_free(void *mm_ptr)
与mm_management_malloc()相反,先检查所有小内存链表是都有该地址,有的话就把该地址内存清0,并把标记设为MM_STATUS_FREE;如果是用malloc申请的,当时是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:表示内存空闲
#define MM_STATUS_BUSY (1) //1:表示内存已被申请
#define MM_STATUS_OK (0)
#define MM_STATUS_FAIL (1)
typedef struct mm_node_struct {
unsigned int *mm_node; //存放内存节点指针
unsigned short iflag; //指针是否空闲
struct P_MM_Node_STRUCT *next; //指向下一个内存节点指针
} 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 =