您的位置:首页 > 其它

单片机(不基于os)下如何实现简单的内存管理(malloc,realloc和free函数的重新实现)

2012-12-03 10:25 489 查看
实现的原理是将内存分成小的片段进行管理,代码如下:
#defineMEM_BLOCK_SIZE4096
#defineMEM_LARGE_BLOCK_THRESHOLD40960 //>MEM_LARGE_BLOCK_THRESHOLD:requestedsizeislargeblock
#defineMEM_BASE_ADDRESS(0x90000000)
#defineMEM_ALLOC_TABLE_FIRST_ENTRY 0
#defineMAX_MEM_SIZE7*1024*1024
#defineMEM_ALLOC_TABLE_SIZE (MAX_MEM_SIZE/MEM_BLOCK_SIZE)
staticINT16memory_map[MEM_ALLOC_TABLE_SIZE];
staticcharisMemoryManagementReady=0;
void*memset(void*s,intc,size_tcount)
{
char*xs=s;
while(count--)
*xs++=c;
returns;
}

INT32ssd_mem_init(void)
{
memset(memory_map,0,sizeof(memory_map));
isMemoryManagementReady=1;
}
INT16 ssd_mem_percentage_used()
{
intused=0;
inti;
for(i=0;i<MEM_ALLOC_TABLE_SIZE;i++)
{
if(memory_map[i])
{
used++;
}
}
returnused*100/MEM_ALLOC_TABLE_SIZE;
}
//return-1:FAIL
//>=0: returnallocatedaddressoffset
INT32ssd_mem_malloc(UINT32size)
{
intoffset=0;
intstartEntry=MEM_ALLOC_TABLE_FIRST_ENTRY;
intnmemb;
inti;
if(!isMemoryManagementReady)
{
ssd_mem_init();
}

if(size==0)
{
return-1;
}
nmemb=size/MEM_BLOCK_SIZE;
if(size%MEM_BLOCK_SIZE)
{
nmemb++;
}

if(size>MEM_LARGE_BLOCK_THRESHOLD)
{
for(offset=startEntry;offset<MEM_ALLOC_TABLE_SIZE-nmemb;offset++)
{
if(!memory_map[offset])
{
intvacantSize=0;
for(vacantSize=0;vacantSize<nmemb&&!memory_map[offset+vacantSize];vacantSize++);
if(vacantSize==nmemb)
{
for(i=0;i<nmemb;i++)
{
memory_map[offset+i]=nmemb;
}
return(offset*MEM_BLOCK_SIZE);
}
}
}
}
else
{
for(offset=MEM_ALLOC_TABLE_SIZE-1;offset>=0;offset--)
{
if(!memory_map[offset]&&((offset+nmemb)<=MEM_ALLOC_TABLE_SIZE))//searchstartofvacantblock
{

intvacantSize=0;
for(vacantSize=0;vacantSize<nmemb&&!memory_map[offset+vacantSize];vacantSize++);
if(vacantSize==nmemb)
{
for(i=0;i<nmemb;i++)
{
memory_map[offset+i]=nmemb;
}
return(offset*MEM_BLOCK_SIZE);
}
}
}
}
puts("mallocsizeerorr=");
putInt32(size);
return-1;
}
//return0:OK
//return1:Outofbound
INT32ssd_mem_free(INT32offset)
{
inti;
if(!isMemoryManagementReady)
{
ssd_mem_init();
return1;
}
if(offset<MAX_MEM_SIZE)
{
intindex=offset/MEM_BLOCK_SIZE;
intnmemb=memory_map[index];
for(i=0;i<nmemb;i++)
{
memory_map[index+i]=0;
}
return0;
}
else
{
return1;//outofbound
}
}
voidfree(void*ptr)
{
if(ptr==NULL)
return;
INT32offset;
offset=ptr-MEM_BASE_ADDRESS;
ssd_mem_free(offset);
}
void*malloc(UINT32size)
{
INT32offset;
offset=ssd_mem_malloc(size);
if(offset==-1)
{
returnNULL;
}
else
returnMEM_BASE_ADDRESS+offset;

}

void*realloc(void*ptr,UINT32size)
{
INT32offset;
offset=ssd_mem_malloc(size);
if(offset==-1)
{
puts("reallocerror/n");
returnNULL;
}
else
{
memcpy((void*)(MEM_BASE_ADDRESS+offset),ptr,size);
free(ptr);
returnMEM_BASE_ADDRESS+offset;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐