一、概述

        在嵌入式软件开发中,或多或少会用到动态内存分配而一般的IDE自带的标准malloc/realloc/free函数存在一些问题,例如:并发情况下存在竞争问题、长期运行时会导致内存碎片暴涨、长期运行时通过malloc/realloc调用时导致时间超时等其他问题。所以基于上诉问题进行改进自己手动实现一个内存管函数在长期运行时可以通过合并部分碎片让内存碎片显著下降,在多任务情况下有条件的避免并发竞争导致的资源分配错乱并且对于实时性较强的系统避免单次malloc/realloc/free函数执行时间过长。

二、实现方法介绍

1、 实现内存池要有以下优点:

(1)、实现过程不能太复杂避免单次运行代码时间过长调试过程变得复杂;

(2)、要有高效的管理策略让每次分配查找适应内存时时间都变得短而确定;

(3)、不要有复杂的特性让代码尽量适应不同的运行平台;

(4)、采用最佳适配策略,尽量保存较大内存块减少因找不到足够大的内存块时失败的情况;

2、结构设计:

        下面我将介绍基于上述描述的特点设计了一种链表结构,当然也会有其它适合的数据结构我这里设计链表结构比较简单实现。

        主链—次链复合链表的结构,主链负责较大范围节点的管理而次链负责较细的范围节点管理。比如要管理1024个不同节点范围数据,此时把主链划分每隔32范围进行遍历查找而次链则是这每隔32数据里比较细数据数据管理,这样主链最长32个节点而次链最长也是32个节点;当我们每次遍历时最差的情况下只需遍历64次,这样就完成这个结构的最基本的逻辑结构,为了进一步优化在主链—次链的结构上添加等链,等链是为了处理节点长度相等情况;因为在实际分配节点过程必会相同的节点如果把等链只添加到主链—次链结构上必会增加查找节点的长度,但变成主链—次链—等链的结构每次只需要从相同的节点下获取第一个等链节点就行了此过程并不会增加整个结构的长度。

三、图文结构介绍:

1、主链—次链结构

2、等链节点

3、单个节点变换

四、源码实现

Chain_Management.h文件实现

#ifndef  MEMORY_LIST_H
#define  MEMORY_LIST_H

#define NULL ((void*)0)

#define OFFSET_BYTE 8

typedef unsigned int UINT_L;

typedef unsigned char Byte;

typedef struct Memory_Block Memory_Block;

static void Chain_add(Memory_Block* Add);

static Memory_Block* Chain_find(UINT_L Length);

static void Chain_delete(Memory_Block* Del);

extern Byte Init_malloc(void* start_addr, UINT_L Length, void (*Lock_State)(void), void (*Unlock_State)(void));

extern void* My_malloc(UINT_L Length);

extern void* My_realloc(void* ptr, UINT_L Length);

extern void My_free(void* addr);

extern void UnInit_malloc(void);

extern UINT_L Get_Current_Block_size(void);

extern UINT_L Get_Current_Available(void);

extern UINT_L Get_Total_Length(void);

extern UINT_L Get_Used_MemLen(void);

extern UINT_L Get_Current_Max_Len(void);

extern UINT_L Get_Current_Min_Len(void);

extern UINT_L Get_Current_ListNode(void);

extern UINT_L Get_Current_MemLen(void* addr);

extern UINT_L Check_Control_Data(void* addr);

extern void* My_malloc_Safe(UINT_L size);

extern void My_free_Safe(void* addr);

extern void* My_realloc_Safe(void* ptr, UINT_L Length);

extern void Memory_Reset(void* addr, UINT_L Length);

extern void* Memcpy_s(void* destinction, void* orignal, UINT_L Length);

#endif

Chain_Management.c文件实现

#include"Chain_Management.h"

typedef struct Memory_Base
{
	UINT_L Block_size : sizeof(UINT_L) * 8 - 1;
	UINT_L flat : 1;
}Memory_Base;

typedef struct Memory_Block
{
	volatile Memory_Base block;
	struct Memory_Block* front;
	struct Memory_Block* back;
	struct Memory_Block* equal;
	struct Memory_Block* down;
}Memory_Block;

typedef struct Head_Info
{
	UINT_L length;
	UINT_L Block_size;
	UINT_L avaliable_block;
	UINT_L Down_Info;
	UINT_L List_Node_Count;
	Memory_Block* start_addr;
	Memory_Block* Head;
	void (*Lock_State)(void);//锁状态
	void (*Unlock_State)(void);//解锁状态
}Head_Info;

volatile Head_Info* Memory_Head = NULL;

#define ALIGN_SIZE(size) (((size) + ((OFFSET_BYTE) - 1)) & ~((OFFSET_BYTE) - 1))

//添加节点
static void Chain_add(Memory_Block* Add)
{
	UINT_L Heigh_Info = ~(Memory_Head->Down_Info);
	UINT_L Heigh_Bit = Add->block.Block_size & Heigh_Info;
	Memory_Block* Goal_Heigh = Memory_Head->Head;

	Add->back = Add->down = Add->equal = Add->front = NULL;
	Add->block.flat = 0;

	Memory_Block* Heigh_Pre = NULL;
	while (Goal_Heigh != NULL && Goal_Heigh->block.Block_size < Heigh_Bit)
	{//从小到大排列
		Heigh_Pre = Goal_Heigh;
		Goal_Heigh = Goal_Heigh->back;
	}
	if (Goal_Heigh == NULL || (Goal_Heigh->block.Block_size & Heigh_Info) != Heigh_Bit)
	{//当链接节点属于主链上的情况时
		if (Heigh_Pre == NULL)
			Memory_Head->Head = Add;
		else
			Add->front = Heigh_Pre, Heigh_Pre->back = Add;
		if (Goal_Heigh != NULL) Add->back = Goal_Heigh, Goal_Heigh->front = Add;
	}
	else
	{//当链接节点属于次链上的情况时
		Memory_Block* Low_Pre = NULL;
		Memory_Block* Goal_Low = Goal_Heigh;
		while (Goal_Low != NULL && Goal_Low->block.Block_size > Add->block.Block_size)
		{//从大到小排列
			Low_Pre = Goal_Low;
			Goal_Low = Goal_Low->down;
		}
		if (Goal_Low != NULL && Goal_Low->block.Block_size == Add->block.Block_size)
		{//判断是否等于相同链上的节点
			Add->front = Goal_Low, Add->equal = Goal_Low->equal;
			if (Goal_Low->equal != NULL) Goal_Low->equal->front = Add;
			Goal_Low->equal = Add;
		}
		else if (Low_Pre == NULL)
		{//判断是否为主链上的点
			Add->front = Goal_Low->front, Add->back = Goal_Low->back, Add->down = Goal_Low;
			if (Goal_Low->front == NULL)
				Memory_Head->Head = Add;
			else
				Goal_Low->front->back = Add;
			if (Goal_Low->back != NULL) Goal_Low->back->front = Add, Goal_Low->back = NULL;
			Goal_Low->front = Add;
		}
		else
		{//添加到次链上
			Low_Pre->down = Add, Add->front = Low_Pre;
			if (Goal_Low != NULL)  Add->down = Goal_Low, Goal_Low->front = Add;
		}
	}
	Memory_Head->List_Node_Count++;
}

//查找节点
static Memory_Block* Chain_find(UINT_L Length)
{
	Memory_Block* Goal_Heigh = Memory_Head->Head;
	while (Goal_Heigh != NULL && Goal_Heigh->block.Block_size < Length)
	{
		Goal_Heigh = Goal_Heigh->back;
	}
	if (Goal_Heigh == NULL) return NULL;
	Memory_Block* Goal_Low = Goal_Heigh;
	while (Goal_Low->down != NULL && Goal_Low->block.Block_size > Length)
	{
		Goal_Low = Goal_Low->down;
	}
	return Goal_Low->equal == NULL ? Goal_Low : Goal_Low->equal;
}

//删除节点
static void Chain_delete(Memory_Block* Del)
{
	Memory_Block* Del_Replace = NULL;
	Memory_Block* Del_Front = Del->front;
	//判断删除节点的位置
	if (Del_Front == NULL || Del_Front->back == Del)
	{//如果是主链上的节点
		if (Del->equal != NULL)
		{//如果存在等链上的节点
			Del_Replace = Del->equal;//用等链上的节点替换删除节点
			Del_Replace->front = Del->front, Del_Replace->back = Del->back, Del_Replace->down = Del->down;
			if (Del_Front != NULL) Del_Front->back = Del_Replace;
			if (Del->back != NULL) Del->back->front = Del_Replace;
			if (Del->down != NULL) Del->down->front = Del_Replace;
		}
		else if (Del->down != NULL)
		{//如果存在次链上的节点
			Del_Replace = Del->down;//用次链上的节点替换删除节点
			Del_Replace->front = Del->front, Del_Replace->back = Del->back;
			if (Del_Front != NULL) Del_Front->back = Del_Replace;
			if (Del->back != NULL) Del->back->front = Del_Replace;
		}
		else if(Del->back != NULL)
		{//如果存在后继节点
			Del_Replace = Del->back;//用后继节点替换删除节点
			Del_Replace->front = Del->front;
			if (Del_Front != NULL) Del_Front->back = Del_Replace;
		}
		else
		{//没有后继节点
			if (Del_Front != NULL) Del_Front->back = NULL;
		}
		if (Del->front == NULL) Memory_Head->Head = Del_Replace;
	}
	else if (Del_Front->down == Del)
	{//如果是次链上的节点
		if (Del->equal != NULL)
		{//如果存在等链上的节点
			Del_Replace = Del->equal;//用等链上的节点替换删除节点
			Del_Replace->front = Del->front, Del_Replace->down = Del->down;
			Del_Front->down = Del_Replace;
			if (Del->down != NULL) Del->down->front = Del_Replace;
		}
		else if(Del->down != NULL)
		{//如果存在后继节点
			Del_Replace = Del->down;//用后继节点替换删除节点
			Del_Replace->front = Del->front;
			Del_Front->down = Del_Replace;
		}
		else
		{//没有后继节点
			Del_Front->down = NULL;
		}
	}
	else
	{//如果是等链上的节点
		if (Del->equal != NULL)
		{//如果存在等链上的节点
			Del_Replace = Del->equal;//用等链上的节点替换删除节点
			Del_Replace->front = Del->front;
		}
		Del_Front->equal = Del_Replace;
	}
	Del->block.flat = 1;//标记为已分配状态
	Memory_Head->List_Node_Count--;//更新节点数量
}

//初始化内存池
extern Byte Init_malloc(void* start_addr, UINT_L Length, void (*Lock_State)(void), void (*Unlock_State)(void))
{
	UINT_L N = 0, Factor = 0;
	UINT_L Sum_Length = 0 , Down_Sum = 0;
	//初始化检查
	if (Length < (ALIGN_SIZE(sizeof(Memory_Head)) + 2 * ALIGN_SIZE(sizeof(Memory_Block)) + sizeof(Memory_Block*))) return 0;//内存池过小无法初始化
	if ((UINT_L)start_addr & (OFFSET_BYTE - 1)) start_addr = ((Byte*)start_addr) + (OFFSET_BYTE - ((UINT_L)start_addr & (OFFSET_BYTE - 1))), Length -= (OFFSET_BYTE - ((UINT_L)start_addr & (OFFSET_BYTE - 1)));//地址对齐处理
	//计算内存池信息
	Sum_Length = Length - ALIGN_SIZE(sizeof(Head_Info));
	Down_Sum = Sum_Length / OFFSET_BYTE;
	Memory_Head = (Head_Info*)start_addr;
	Memory_Head->length = Sum_Length;
	Memory_Head->Block_size = Sum_Length / OFFSET_BYTE;
	Memory_Head->avaliable_block = Sum_Length / OFFSET_BYTE;
	//计算下标信息
	Memory_Head->Down_Info = 0;
	for (UINT_L i = Down_Sum; i > 0; i >>= 1, Factor++);
	N = Factor / 2 + 3;//f(x) = [n/2]↓ + 3
	Memory_Head->Down_Info = (0x01 << (N / 2)) - 1;
	//初始化头节点信息
	Memory_Head->start_addr = (Memory_Block*)(((Byte*)start_addr) + ALIGN_SIZE(sizeof(Head_Info)));
	Memory_Head->Head = (Memory_Block*)(((Byte*)start_addr) + ALIGN_SIZE(sizeof(Head_Info)));
	Memory_Head->Head->block.flat = 0;
	Memory_Head->Head->block.Block_size = Sum_Length / OFFSET_BYTE;
	Memory_Head->Head->front = Memory_Head->Head->back = Memory_Head->Head->down = Memory_Head->Head->equal = NULL;
	Memory_Block** End_Info = (Memory_Block**)(((Byte*)Memory_Head->Head) + (Sum_Length / OFFSET_BYTE) * OFFSET_BYTE - sizeof(Memory_Block*));
	*End_Info = Memory_Head->Head;
	Memory_Head->Lock_State = Lock_State;//锁状态函数指针赋值
	Memory_Head->Unlock_State = Unlock_State;//解锁状态函数指针赋值
	Memory_Head->List_Node_Count = 1;
	return 1;
}
//内存池分配
extern void* My_malloc(UINT_L Length)
{
	if (Length == 0)  return NULL;
	const UINT_L Min_size = ALIGN_SIZE(sizeof(Memory_Block)) + sizeof(Memory_Block*);
	UINT_L Sum_size = Length + ALIGN_SIZE(sizeof(Memory_Base)) + sizeof(Memory_Block*);
	Sum_size = Sum_size < Min_size ? Min_size : Sum_size;
	UINT_L Block_size = ALIGN_SIZE(Sum_size) / OFFSET_BYTE;
	Memory_Block* Find = Chain_find(Block_size);
	if (Find == NULL) return NULL;
	Chain_delete(Find);
	UINT_L Min_Block = Block_size + ALIGN_SIZE(Min_size) / OFFSET_BYTE;
	if (Find->block.Block_size >= Min_Block)
	{
		Memory_Block* Isolation = (Memory_Block*)(((Byte*)Find) + Block_size * OFFSET_BYTE);
		Memory_Block** End_Info = (Memory_Block**)(((Byte*)Find) + (Find->block.Block_size * OFFSET_BYTE - sizeof(Memory_Block*)));
		Isolation->block.Block_size = Find->block.Block_size - Block_size;
		Find->block.Block_size = Block_size;
		*End_Info = Isolation;
		End_Info = (Memory_Block**)(((Byte*)Isolation) - sizeof(Memory_Block*));
		*End_Info = Find;
		Chain_add(Isolation);
	}
	else
		Block_size = Find->block.Block_size;
	Memory_Head->avaliable_block -= Block_size;
	return ((Byte*)Find) + ALIGN_SIZE(sizeof(Memory_Base));
}
//重新分配内存
extern void* My_realloc(void* ptr, UINT_L Length)
{
	void* addr = ptr;
	Memory_Block** Ptr_End = NULL;
	Memory_Block* Division_addr = NULL;
	if (ptr == NULL) return My_malloc(Length);
	if (Length == 0){My_free(ptr);return NULL;}
	//计算申请内存的大小
	const UINT_L Min_size = ALIGN_SIZE(sizeof(Memory_Block)) + sizeof(Memory_Block*);
	UINT_L Sum_size = Length + ALIGN_SIZE(sizeof(Memory_Base)) + sizeof(Memory_Block*);
	//获取原来块的大小
	Memory_Block* Ptr_Block = (Memory_Block*)(((Byte*)ptr) - ALIGN_SIZE(sizeof(Memory_Base)));
	UINT_L Ptr_len = Ptr_Block->block.Block_size;
	//计算申请改变的块的大小
	Sum_size = Sum_size < Min_size ? Min_size : Sum_size;
	UINT_L Block_size = ALIGN_SIZE(Sum_size) / OFFSET_BYTE;
	if (Ptr_len > Block_size)
	{//如果申请的块比原来的块小
		UINT_L Min_Block = Block_size + ALIGN_SIZE(Min_size) / OFFSET_BYTE;
		if (Ptr_len >= Min_Block)
		{//判断块是否能被再分割
			Division_addr = (Memory_Block*)(((Byte*)Ptr_Block) + (ALIGN_SIZE(Sum_size)));//获取分割的地址
			Ptr_End = (Memory_Block**)(((Byte*)Ptr_Block) + ((Ptr_Block->block.Block_size * OFFSET_BYTE) - sizeof(Memory_Block*)));
			Division_addr->block.Block_size = Ptr_Block->block.Block_size - Block_size, * Ptr_End = Division_addr;//分割快数据初始化
			Ptr_End = (Memory_Block**)(((Byte*)Division_addr) - sizeof(Memory_Block*)), Ptr_Block->block.Block_size = Block_size;
			*Ptr_End = Ptr_Block, Division_addr->block.flat = 1;
			My_free(((Byte*)Division_addr) + ALIGN_SIZE(sizeof(Memory_Base)));//分割块入链表
		}
	}
	else if (Ptr_len < Block_size)
	{//如果申请的块比原来的块大
		Memory_Block* Add_addr = (Memory_Block*)(((Byte*)Ptr_Block) + (Ptr_Block->block.Block_size * OFFSET_BYTE));//找出相邻下个块的位置
		if (Add_addr < (Memory_Head->start_addr + Memory_Head->length) && Add_addr->block.flat == 0 && (Add_addr->block.Block_size + Ptr_len) >= Block_size)
		{//如果存在充足的后块
			Chain_delete(Add_addr);//取出块
			UINT_L Remian_Block = (Add_addr->block.Block_size + Ptr_len) - Block_size;//计算剩余块的大小
			if (Remian_Block >= (ALIGN_SIZE(Min_size) / OFFSET_BYTE))//分割块
			{//满足分割
				Add_addr = (Memory_Block*)(((Byte*)Add_addr) + (Block_size - Ptr_len) * OFFSET_BYTE);//计算分割块的位置
				Add_addr->block.Block_size = Remian_Block, Ptr_End = (Memory_Block**)(((Byte*)Add_addr) + Remian_Block * OFFSET_BYTE - sizeof(Memory_Block*));//分割块初始化
				*Ptr_End = Add_addr;
				Chain_add(Add_addr);
			}
			else//不满足分割
				Block_size = Add_addr->block.Block_size + Ptr_len;//将相邻的后块全部纳入整个块中
			Ptr_Block->block.Block_size = Block_size;//整个新块重新初始化
			Ptr_End = (Memory_Block**)(((Byte*)Ptr_Block) + Block_size * OFFSET_BYTE - sizeof(Memory_Block*));
			*Ptr_End = Ptr_Block;
			Memory_Head->avaliable_block -= (Block_size - Ptr_len);
		}
		else
		{//重新申请内存块
			addr = Add_addr = My_malloc(Length);
			if (addr == NULL) return NULL;
			UINT_L Data_len = (Ptr_len * OFFSET_BYTE) - (ALIGN_SIZE(sizeof(Memory_Base)) + sizeof(Memory_Block*));
			for (unsigned int i = 0; i < Data_len; i++)	((Byte*)Add_addr)[i] = ((Byte*)ptr)[i];
			My_free(ptr);
		}
	}
	return addr;
}
//内存池释放
extern void My_free(void* addr)
{
	if (addr == NULL) return;
	Memory_Block* Free_Block = (Memory_Block*)(((Byte*)addr) - ALIGN_SIZE(sizeof(Memory_Base)));
	UINT_L Free_len = Free_Block->block.Block_size;
	Memory_Block* Pre_Free = NULL, * Next_Free = NULL;
	if (Free_Block->block.flat == 0) return;
	//前区合并
	if (Free_Block != Memory_Head->start_addr)
	{
		Pre_Free = *((Memory_Block**)(((Byte*)Free_Block) - sizeof(Memory_Block*)));
		if (Pre_Free->block.flat == 0)
		{
			Chain_delete(Pre_Free);
			Pre_Free->block.Block_size += Free_len;
			Free_Block = Pre_Free;
		}
	}
	//后区合并
	if ((((((Byte*)Free_Block) - ((Byte*)(Memory_Head->start_addr))) / OFFSET_BYTE) + Free_Block->block.Block_size) != Memory_Head->Block_size)
	{
		Next_Free = (Memory_Block*)(((Byte*)Free_Block) + Free_Block->block.Block_size * OFFSET_BYTE);
		if (Next_Free->block.flat == 0)
		{
			Chain_delete(Next_Free);
			Free_Block->block.Block_size += Next_Free->block.Block_size;
		}
	}
	//更新新节点情况
	Memory_Block** End_Info = (Memory_Block**)((Byte*)Free_Block + (Free_Block->block.Block_size * OFFSET_BYTE - sizeof(Memory_Block*)));
	*End_Info = Free_Block;
	Chain_add(Free_Block);
	Memory_Head->avaliable_block += Free_len;
}
//反初始化
extern void UnInit_malloc(void)
{
	Memory_Head = NULL;
}
//获取总内存大小
extern UINT_L Get_Current_Block_size(void)
{
	if (Memory_Head == NULL) return 0;
	return Memory_Head->Block_size * OFFSET_BYTE;
}
//获取当前可用内存
extern UINT_L Get_Current_Available(void)
{
	if (Memory_Head == NULL) return 0;
	return Memory_Head->avaliable_block * OFFSET_BYTE;
}
//获取内存池总大小
extern UINT_L Get_Total_Length(void)
{
	if (Memory_Head == NULL) return 0;
	return Memory_Head->length;
}
//获取已使用内存大小
extern UINT_L Get_Used_MemLen(void)
{
	if (Memory_Head == NULL) return 0;
	return (Memory_Head->Block_size - Memory_Head->avaliable_block) * OFFSET_BYTE;
}
//获取当前最大可用块长度
extern UINT_L Get_Current_Max_Len(void)
{
	if (Memory_Head == NULL || Memory_Head->Head == NULL) return 0;
	Memory_Block* Goal_Heigh = Memory_Head->Head;
	while (Goal_Heigh != NULL && Goal_Heigh->back != NULL)
	{
		Goal_Heigh = Goal_Heigh->back;
	}
	return Goal_Heigh == NULL ? 0 : Goal_Heigh->block.Block_size;
}
//获取当前最小可用块长度
extern UINT_L Get_Current_Min_Len(void)
{
	if (Memory_Head == NULL || Memory_Head->Head == NULL) return 0;
	Memory_Block* Goal_Heigh = Memory_Head->Head;
	while (Goal_Heigh != NULL && Goal_Heigh->down != NULL)
	{
		Goal_Heigh = Goal_Heigh->down;
	}
	return Goal_Heigh == NULL ? 0 : Goal_Heigh->block.Block_size;
}
//获取当前可用节点数量
extern UINT_L Get_Current_ListNode(void)
{
	if (Memory_Head == NULL) return 0;
	return Memory_Head->List_Node_Count;
}
//获取动态内存的可用大小
extern UINT_L Get_Current_MemLen(void *addr)
{
	Memory_Base *Mem_addr = NULL;
	if (addr == NULL) return 0;
	Mem_addr = (Memory_Base*)(((Byte*)addr) - ALIGN_SIZE(sizeof(Memory_Base)));
	return Mem_addr->Block_size * OFFSET_BYTE - ALIGN_SIZE(sizeof(Memory_Base)) - sizeof(Memory_Block*);
}
//检查元数据数据是否被破坏
extern UINT_L Check_Control_Data(void* addr)
{
	if (addr == NULL || Memory_Head == NULL || addr < Memory_Head->start_addr || addr > ((Memory_Head->Block_size * OFFSET_BYTE) + (Byte*)Memory_Head->start_addr)) return 0;//地址不合法
	Memory_Base* addr_info = (Memory_Base*)((Byte*)addr - ALIGN_SIZE(sizeof(Memory_Base)));//获取块的控制信息地址
	if (((Byte*)addr_info + (addr_info->Block_size * OFFSET_BYTE)) > ((Memory_Head->Block_size * OFFSET_BYTE) + (Byte*)Memory_Head->start_addr)) return 0;//地址不合法
	Memory_Block* addr_end = *((Memory_Block**)(((Byte*)addr_info) + addr_info->Block_size * OFFSET_BYTE - sizeof(Memory_Block*)));//获取结束节点地址
	return (addr_end == (Memory_Block*)addr_info) ? 1 : 0;//返回检查结果:1正确    0错误
}
//线程安全的内存申请接口
extern void* My_malloc_Safe(UINT_L size)
{
	void* addr = NULL;
	if (Memory_Head->Lock_State != NULL) Memory_Head->Lock_State();
	addr = My_malloc(size);
	if (Memory_Head->Unlock_State != NULL) Memory_Head->Unlock_State();
	return addr;
}
//线程安全的内存释放接口
extern void My_free_Safe(void* addr)
{
	if (Memory_Head->Lock_State != NULL) Memory_Head->Lock_State();
	My_free(addr);
	if (Memory_Head->Unlock_State != NULL) Memory_Head->Unlock_State();
}
//线程安全的内存重新分配接口
extern void* My_realloc_Safe(void* ptr, UINT_L Length)
{
	void* addr = NULL;
	if (Memory_Head->Lock_State != NULL) Memory_Head->Lock_State();
	addr = My_realloc(ptr, Length);
	if (Memory_Head->Unlock_State != NULL) Memory_Head->Unlock_State();
	return addr;
}
//内存重置
extern void Memory_Reset(void* addr, UINT_L Length)
{
	Byte* addr_byte = (Byte*)addr;
	long long* addr_int = NULL;
	UINT_L Len = 0;
	if (addr == NULL || Length == 0) return;
	// 地址处理非对齐部分
	for (; Length && ((Byte)addr_byte & (sizeof(long long) - 1)); Length--)
	{
		*addr_byte++ = 0;
	}
	addr_int = (long long*)addr_byte;
	Len = Length / sizeof(long long);
	for (; Len; Len--)
	{
		*addr_int++ = 0;
	}
	//剩余部分处理
	Len = Length % sizeof(long long);
	addr_byte = (Byte*)addr_int;
	for (; Len; Len--)
	{
		*addr_byte++ = 0;
	}
}

extern void* Memcpy_s(void* destinction, void* orignal, UINT_L Length)
{//下面的代码未考虑内存对齐问题
	Byte* dest = (Byte*)destinction;
	Byte* orign = (Byte*)orignal;
	long long* dest_int = NULL;
	long long* orign_int = NULL;
	UINT_L Len = Length % sizeof(long long);
	if (!destinction || !orignal || Length == 0)  return NULL;
	if ((dest > orign) && ((orign + Length) > dest))
	{
		// 当目的地址大于源地址并且复制的长度大于源地址时
		dest += Length;
		orign += Length;
		for (; Len; Len--)
		{
			*(--dest) = *(--orign);
		}
		Len = Length / sizeof(long long);
		dest_int = (long long*)dest;
		orign_int = (long long*)orign;
		for (; Len; Len--)
		{
			*(--dest_int) = *(--orign_int);
		}
	}
	else
	{
		for (; Len; Len--)
		{
			*dest++ = *orign++;
		}
		Len = Length / sizeof(long long);
		dest_int = (long long*)dest;
		orign_int = (long long*)orign;
		for (; Len; Len--)
		{
			*dest_int++ = *orign_int++;
		}
	}

	return destinction;
}

Test.c测试文件实现

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include "Chain_Management.h"

// 自定义内存管理系统的测试
void test_custom_malloc()
{
    int** P = (int**)malloc(sizeof(int*) * 10000);
    if (P == NULL) return;

    // 进行1000 0000次申请操作
    printf("Test Custom Malloc 开始\n");
    clock_t t = clock();

    // 初始化指针数组
    for (int i = 0; i < 10000; i++)
        P[i] = NULL;

    for (int i = 0; i < 10000000; i++)
    {
        if (rand() % 2 == 0 && P[i % 10000] == NULL)
        {
            P[i % 10000] = (int*)My_realloc(P[i % 10000],rand());
        }
        else
        {
            My_free(P[i % 10000]);
            P[i % 10000] = NULL;
        }
    }

    printf("自制内存管理耗时 %lu ms\n", (clock() - t) * 1000 / CLOCKS_PER_SEC);

    // 指针数组归零
    for (int i = 0; i < 10000; i++)
    {
        My_free(P[i]);
        P[i] = NULL;
    }

    free(P);
    printf("Test Custom Malloc 完成\n\n");
}

// 标准库 malloc 的测试
void test_standard_malloc()
{
    int** P = (int**)malloc(sizeof(int*) * 10000);
    if (P == NULL) return;

    // 进行1000 0000次申请操作
    printf("Test Standard Malloc 开始\n");
    clock_t t = clock();

    // 初始化指针数组
    for (int i = 0; i < 10000; i++)
        P[i] = NULL;

    for (int i = 0; i < 10000000; i++)
    {
        if (rand() % 2 == 0 && P[i % 10000] == NULL)
        {
            P[i % 10000] = (int*)malloc(rand());
        }
        else
        {
            free(P[i % 10000]);
            P[i % 10000] = NULL;
        }
    }

    printf("标准库 malloc 耗时 %lu ms\n", (clock() - t) * 1000 / CLOCKS_PER_SEC);

    // 指针数组归零
    for (int i = 0; i < 10000; i++)
    {
        free(P[i]);
        P[i] = NULL;
    }

    free(P);
    printf("Test Standard Malloc 完成\n\n");
}

// 测试函数
int main(void)
{
    srand(time(NULL));
    void* start_addr = malloc(1024*1024 * 1024);
    Init_malloc(start_addr, 1024*1024 * 1024, NULL, NULL);

    test_standard_malloc();

    printf("初始可用内存: %u Byte\n", Get_Current_Available());
    test_custom_malloc();
    printf("自定义内存管理系统测试后可用内存: %u Byte\n", Get_Current_Available());

    char *str= (char*)My_malloc(100);
    Memory_Reset(str,100);
    Memcpy_s(str+20,"Hello World",12);
    printf("%s\n",str+20);
    Memcpy_s(str+25,str+20,12);
    printf("%s\n", str+25);
    free(start_addr);
    system("pause");
    return 0;
}

Logo

openvela 操作系统专为 AIoT 领域量身定制,以轻量化、标准兼容、安全性和高度可扩展性为核心特点。openvela 以其卓越的技术优势,已成为众多物联网设备和 AI 硬件的技术首选,涵盖了智能手表、运动手环、智能音箱、耳机、智能家居设备以及机器人等多个领域。

更多推荐