linux c malloc段错误,在C中实现malloc,realloc,free时出现段错误

本文档展示了一个简单的malloc, realloc和free的实现,使用了一个空闲列表来跟踪已分配的内存块。malloc能够成功分配内存,但realloc在尝试释放旧内存并分配新内存时遇到问题,导致seg错误。问题可能在于free()调用中。代码包括获取空闲块、请求新块以及更新内存块状态的辅助函数。
摘要由CSDN通过智能技术生成

我正在实现一个简单版本的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;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值