发一个我自己写的特简单的malloc/free实现给你参考参考。你只需要自己定义这两个宏:
IMAGE_MALLOC_BUFFER_CA_START
IMAGE_MALLOC_BUFFER_SIZE
使用时记住一点就行了,free的次序必须和malloc相反,换句话说最后分配的最先释放。
/*
* Simple memory allocator for the bootstrap loader.
*/
#include
#define MAX_CHUNK_SIZE IMAGE_MALLOC_BUFFER_SIZE
#define ROUND_UP(x) (((x-1)|3)+1)
#define IS_LAST_CHUNK(p) ( ((char*)p + p->len) >= ((char*)chunklist + MAX_CHUNK_SIZE) )
struct chunk
{
struct chunk *prev;
size_t len;
};
static struct chunk *chunklist = 0;
void* bl_malloc(size_t len)
{
struct chunk *p, *q, *t;
size_t clen;
if (!len) return 0;
clen = ROUND_UP(len) + sizeof(struct chunk);
p = chunklist;
if (p)
{
if (p->len < clen)
return 0;
p->len -= clen;
q = (struct chunk*) ((char*)p + sizeof(struct chunk) + p->len);
q->len = clen;
q->prev = p;
if (!IS_LAST_CHUNK(q))
{
// adjust previous pointer of next chunk
t = (struct chunk*) ((char*)q + q->len);
t->prev = q;
}
q++;
return (void *)q;
}
else
{
chunklist = (struct chunk*)IMAGE_MALLOC_BUFFER_CA_START;
chunklist->prev = 0;
chunklist->len = MAX_CHUNK_SIZE - sizeof(struct chunk);
return bl_malloc(len);
}
}
void bl_free(void *vp)
{
struct chunk *p, *q, *t;
if (!vp) return;
p = (struct chunk*)vp;
p--;
q = p->prev;
if (!IS_LAST_CHUNK(p))
{
// adjust previous pointer of next chunk
t = (struct chunk*) ((char*)p + p->len);
t->prev = q;
}
q->len += p->len;
}