loop + 7) >> 3 - 1] & (0x1 << ((loop + 7) % 8));
if(0 != flag){
return loop;
}
loop ++;
}
return -1;
}
int check_if_data_exist(const DATA_NODE* pDataNode)
{
int number = pDataNode->num;
char* pFlag = pDataNode->pFlag;
unsigned char flag = 0;
int loop = 1;
while(loop <= number){
flag = pFlag[(loop + 7) >> 3 - 1] & (0x1 << ((loop + 7) % 8));
if(0 != flag){
return loop;
}
loop ++;
}
return -1;
} e) 分配内存空间
int* alloca_data(const DATA_NODE* pDataNode)
{
int* pData = NULL;
int pos;
if(NULL == pDataNode)
return NULL;
if(-1 == (pos = check_if_data_exist(pDataNode)))
return NULL;
pDataNode->pFlag[(pos + 7) >> 3 - 1] |= 0x1 << ((pos + 7)% 8);
return pDataNode->pData + (pos - 1);
}
int* alloca_data(const DATA_NODE* pDataNode)
{
int* pData = NULL;
int pos;
if(NULL == pDataNode)
return NULL;
if(-1 == (pos = check_if_data_exist(pDataNode)))
return NULL;
pDataNode->pFlag[(pos + 7) >> 3 - 1] |= 0x1 << ((pos + 7)% 8);
return pDataNode->pData + (pos - 1);
} f)回收内存空间
STATUS free_data(const DATA_NODE* pDataNode, const int* pData)
{
int pos = 0;
if(NULL == pDataNode || NULL == pData)
return FALSE;
if(pData < pDataNode->pData || pData > (pDataNode->pData + pDataNode->num))
return FALSE;
pos = (pData - pDataNode->pData) >> 3;
pDataNode->pFlag[(pos + 7) -1] &= ~(0x1 << ((pos + 7) % 8));
return TRUE;
}
STATUS free_data(const DATA_NODE* pDataNode, const int* pData)
{
int pos = 0;
if(NULL == pDataNode || NULL == pData)
return FALSE;
if(pData < pDataNode->pData || pData > (pDataNode->pData + pDataNode->num))
return FALSE;
pos = (pData - pDataNode->pData) >> 3;
pDataNode->pFlag[(pos + 7) -1] &= ~(0x1 << ((pos + 7) % 8));
return TRUE;
} g)统计当前已经分配了多少DWORD空间
int count_free_space(const DATA_NODE* pDataNode)
{
int count = 0;
int loop = 1;
char flag = 0;
if(NULL == pDataNode)
return 0;
for(; loop <= pDataNode->num; loop++)
{
flag = pDataNode->pFlag[(loop + 7) >> 3 - 1] & (0x1 << ((loop + 7) % 8));
if(0 == flag){
count ++;
}
}
return count;
}
int count_free_space(const DATA_NODE* pDataNode)
{
int count = 0;
int loop = 1;
char flag = 0;
if(NULL == pDataNode)
return 0;
for(; loop <= pDataNode->num; loop++)
{
flag = pDataNode->pFlag[(loop + 7) >> 3 - 1] & (0x1 << ((loop + 7) % 8));
if(0 == flag){
count ++;
}
}
return count;
}
上面的代码只是一个示范,大家可以在这个基础之上加以改进,比如说:
(1)修改成可以自由分配很多内存,注意需要同时修改flag的结构类型
(2)修改成先到先得的内存分配类型
(3)修改成最合适空间的内存分配类型
(4)修改成debug类型的内存分配形式,每次分配和释放的时候都检查内存是否越界、是否没有成对运行,注意需要添加对应的判断函数