c - 在 c 中拥有 free() | 无熔化数据块
问题描述
我必须编写自己的 free & malloc 函数。到目前为止,我对此没有任何问题,但现在我应该在 halde_free() 函数中合并相邻的空闲内存块。如果你能在那里帮助我,我将不胜感激。
#include "halde.h"
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <stdint.h>
/// Magic value for occupied memory chunks.
#define MAGIC ((void*)0xbaadf00d)
/// Size of the heap (in bytes).
#define SIZE (1024*1024*1)
/// Memory-chunk structure.
struct mblock {
struct mblock *next;
size_t size;
char memory[];
};
/// Heap-memory area.
char memory[SIZE];
/// Pointer to the first element of the free-memory list.
static struct mblock *head;
/// Helper function to visualise the current state of the free-memory list.
void halde_print(void) {
struct mblock* lauf = head;
// Empty list
if ( head == NULL ) {
fprintf(stderr, "(empty)\n");
return;
}
// Print each element in the list
while ( lauf ) {
fprintf(stderr, "(addr: 0x%08zx, off: %7zu, ", (uintptr_t) lauf, (uintptr_t)lauf - (uintptr_t)memory);
fflush(stderr);
fprintf(stderr, "size: %7zu)", lauf->size);
fflush(stderr);
if ( lauf->next != NULL ) {
fprintf(stderr, " --> ");
fflush(stderr);
}
lauf = lauf->next;
}
fprintf(stderr, "\n");
fflush(stderr);
}
void *halde_malloc (size_t size) {
static int initialized = 0;
if(initialized == 0){
head = (struct mblock *) memory;
head->size = sizeof(memory) - sizeof (struct mblock);
head->next = NULL;
initialized = 1;
}
if(size == 0){
return NULL;
}
struct mblock *lauf = head;
struct mblock **prev_next = &head;
while (lauf != NULL && lauf->size < size){
prev_next = &(lauf->next);
lauf = *prev_next;
}
if(lauf == NULL){
errno = ENOMEM;
return NULL;
}
if((lauf->size -size) <= sizeof(struct mblock)){
*prev_next = lauf->next;
} else {
//mblock anlegen und init.
struct mblock* neu = (struct mblock*) (lauf->memory + size);
neu->size = lauf->size - sizeof(struct mblock) - size;
neu->next = lauf->next;
//mblock anpassen
lauf->size = size;
//verketten wiederherstellen
*prev_next = neu;
}
lauf->next = MAGIC;
return lauf->memory;
}
void halde_free (void *ptr) {
if(ptr == NULL){
return;
}
struct mblock *mbp = (struct mblock *) ptr - 1;
if(mbp->next != MAGIC){
abort();
} else {
mbp->next = head;
head = mbp;
}
}
该代码到目前为止有效,但我真的不知道如何合并块。内存管理运行在一个简单的链表上。变量 head 指向第一个空闲内存块。
我的想法是直接在 else 部分合并块,但我没有一个好主意。
解决方案
推荐阅读
- python - 什么版本的 python 与 GridDB 兼容?
- html - 图像从 HTML 文档中消失,在 css 中定义它们的大小时
- html - Content showing over the top of tooltip
- javascript - 如何在javascript中从“开启”数组和“关闭”数组创建“开启”数组
- jenkins - 詹金斯在空 grep 结果上失败
- flutter - 我想在单击扩展磁贴时填充此单选按钮,并且当我单击一个扩展磁贴时,我希望另一个关闭
- javascript - 语法错误:赋值表达式的左侧无效
- python - 为什么在访问 .dat 文件时出现 IndexError?
- django - django GET 1 个用户的 last_login 时间和所有用户的列表
- async-await - 错误处理链式函数 async/await try/catch