相关疑难解决方法(0)

malloc实现?

我正在尝试实现mallocfreeC,我不知道如何重用内存.我目前struct看起来像这样:

typedef struct _mem_dictionary {
    void *addr;
    size_t size;
    int freed;
} mem_dictionary;
Run Code Online (Sandbox Code Playgroud)

malloc看起来像这样:

void *malloc(size_t size) {
    void *return_ptr = sbrk(size);
    if (dictionary == NULL) 
        dictionary = sbrk(1024 * sizeof(mem_dictionary));

    dictionary[dictionary_ct].addr = return_ptr;
    dictionary[dictionary_ct].size = size;
    dictionary[dictionary_ct].freed = 1;
    dictionary_ct++;

    return return_ptr;
}
Run Code Online (Sandbox Code Playgroud)

当我释放内存时,我只会将地址标记为0(表示它是免费的).在我看来malloc,我会使用for循环来查找数组中的任何值0,然后将内存分配给该地址.我有点困惑如何实现这一点.

c malloc free memory-management

27
推荐指数
3
解决办法
4万
查看次数

标签 统计

c ×1

free ×1

malloc ×1

memory-management ×1