我正在实现一个简单版本的malloc,realloc,并且可以免费进行分配并且无法进行调试 . 我的代码似乎适用于malloc,但realloc测试导致了seg错误 . 具体来说,传递给free()的指针似乎是个问题 .
有一个“空闲列表”来管理以前分配的内存块列表 . 此列表中的每个节点都维护下一个和前一个块,以及一个int free,当内存可用时设置为1,否则为0 .
void *mm_malloc(size_t size) {
if (size <= 0) return NULL;
struct list_node *node;
if (!list_head) {
node = request_block(size);
list_head = node;
list_tail = node;
} else {
node = get_free_block(size);
if (!node) { //no available existing block
node = request_block(size);
if (!node) { //request failed
return NULL;
}
} else { //available existing block
//TODO: split block
node->free = 0;
}
}
return memset(node+1, 0, node->size);
}
void *mm_realloc(void *ptr, size_t size) {
if (size <= 0) return NULL;
if (!ptr) return mm_malloc(size);
struct list_node *node = (struct list_node*)ptr - 1;
if (node->size >= size) {
// TODO: free extra space
return ptr;
}
void *new_block = mm_malloc(size);
if (!new_block) return NULL;
memcpy(new_block, ptr, node->size);
free(ptr); //Error happens with this call.
return new_block;
}
void mm_free(void *ptr) {
if (!ptr) return;
struct list_node *node = (struct list_node*)ptr - 1;
node->free = 1;
}
编辑:遗漏了一些重要的帮助函数
struct list_node *get_free_block(size_t size) {
struct list_node *curr = list_head;
while (curr && !(curr->free && curr->size >= size)) {
curr = curr->next;
} return curr;
}
struct list_node *request_block(size_t size) {
struct list_node *node = sbrk(0);
void *request = sbrk(size + NODE_SIZE);
if (request == (void*) -1) { // attempted sbrk failed
return NULL;
}
if (list_tail) {
node->prev = list_tail;
list_tail->next = node;
list_tail = node;
}
node->next = NULL;
node->free = 0;
node->size = size;
return node;
}