C语言编写可以实现malloc() & free()功能的函数(空间/时间复杂度低)
程序员文章站
2022-05-12 11:28:55
...
#include <stdio.h>
typedef struct _BLOCK //定义一个结构体,用于记录所有可用区块的大小及位置
{
unsigned int size;
struct _BLOCK xdata* pLink;
}BLOCK,xdata* PBLOCK;
PBLOCK xdata pHead = NULL;
//
// Initialize
// Init the Block
//
// Formal Parameters:
// memory = the address of memory
// len = the size of the memory
//
// Global Input Parameters:
// None
//
// Global Output Parameters:
// None
//
// Return Value:
// None
//
void
MemInitializePool(
void* memory,
unsigned len
)
{
pHead = (PBLOCK)memory; //头结点指向自定义用于分配内存的空间
pHead->pLink = NULL;
pHead->size = len;
}
//
// MyMalloc
// malloc the space
//
// Formal Parameters:
// needSize = size of the Block we need
//
// Global Input Parameters:
// None
//
// Global Output Parameters:
// None
//
// Return Value:
// result = the location of the Block
//
void*
MemAlloc(
unsigned int needSize
)
{
PBLOCK pPrior,pNext,pNewNode;
void* result;
pNext = pHead;
pPrior = pHead;
do
{
if ( pNext->size >= needSize ) //寻找到合适大小的空白区块
{
pNext->size = pNext->size - needSize - sizeof(BLOCK); //分配空间出去
pNewNode = (PBLOCK)((void*)pNext + pNext->size + sizeof(BLOCK));//得到存储信息的空间的地址
pNewNode->size = needSize; //可使用的空间大小
if(pNext->size < sizeof(BLOCK))
{
pPrior->pLink = pNext->pLink;
}
result = (void*)(++pNewNode);//返回分配出去的空间地址
return result;
}
pPrior = pNext;
pNext = pNext->pLink;
}while ( pNext != NULL );
if(pNext == NULL) //over
{
return NULL;
}
}
//
// merge
// merge the Block we needn't use
//
// Formal Parameters:
// pPrior = the node of the Link
// pNext = the pLink node of the Link
//
// Global Input Parameters:
// None
//
// Global Output Parameters:
// None
//
// Return Value:
// None
//
void
Merge(
PBLOCK pPrior,
PBLOCK pNext
)
{
if ( pNext == (PBLOCK)((void*)pPrior + pPrior->size + sizeof(PBLOCK)) ) //如果两个空白区块连续,合并空间
{
pPrior->size += (pNext->size) + sizeof(BLOCK);
pPrior->pLink = pNext->pLink;
}
}
//
// MemFree
// free the Block we used
//
// Formal Parameters:
// pBlock = the location of the Block we need to free
//
// Global Input Parameters:
// None
//
// Global Output Parameters:
// None
//
// Return Value:
// None
//
void
MemFree(
PBLOCK pBlock
)
{
PBLOCK pFree = (--pBlock);
PBLOCK pNext = pHead;
PBLOCK pPrior = pHead;
do
{
pPrior = pNext;
pNext = pNext->pLink;
if( pPrior <= pFree && pNext >= pFree) //找到所需要释放的区块的位置
{
pFree->pLink = pNext;
pPrior->pLink = pFree;
break;
}
}while ( pNext != NULL );
//合并空白区块
Merge(
pPrior,
pFree
);
Merge(
pFree,
pNext
);
}
下一篇: 20201224