首页 > 解决方案 > 使用 char 数组填充 C 中的结构

问题描述

我正在用 C 编写一个简单的解释器,我不想处理内存管理,所以我正在编写一个简单的内存池来跟踪和减少 malloc 和 free 的数量。

typedef struct object {

    Type type;
    char data[128];
    struct object* next;

} Object;

typedef struct pool {

    Object* head;
    unsigned int used;
    Object* blocks;

} Pool;

如您所见,我的内存池目前只是一个“对象”的链表,每个对象的大小为 128 字节。

我的 init 和 malloc 函数如下:

#define BLOCK_COUNT 256

void* mp_init() {

    Pool* mp = malloc(1 * sizeof(Pool));

    mp->blocks = malloc(BLOCK_COUNT * sizeof(Object));

    mp->head = mp->blocks;
    mp->blocks->next = NULL;
    mp->used = 0;

    return mp;

}

void* mp_malloc(Pool* mp) {

    Object* obj = NULL;
    obj = (mp->blocks + mp->used);
    obj->next = (mp->blocks + (mp->used + 1) );
    obj->next->next = NULL;

    mp->used++;

    return obj;

}

我正在使用char data[128]强制我的所有对象的大小为 128 字节,我的 malloc 函数返回每个对象的地址,然后我在这 128 字节中存储我想要的任何内容。这是不好的做法吗?仅使用数组来增加结构的大小似乎很奇怪。

标签: cmemorymemory-management

解决方案


It is okay to allocate all the memory your application needs during initialization if:

  1. You don't want your malloc calls to fail due to insufficient memory at run time. (This could be a rare scenario but your application should be robust enough to handle it)

  2. Your application cannot tolerate latency introduced by system calls such as malloc and free.

Whether it is a good practice or not depends on the type of application you are working on. From the code snippet you have posted i would like to give couple of comments:

  1. For sure you have to implement your own mp_free call to return the freed block back to the memory pool.

  2. If your application frees a block in the middle of the list, your mp_malloc should be able to reuse it.

  3. If all your threads are accessing the same memory pool, you need to ensure that the calls to mp_malloc and mp_free are made thread safe.

So in short, implementing your own memory management model is a good practice only when your memory manager is robust enough to handle all the above scenarios and many more. Remember that in large scale applications, a bug in a memory manager could be very hard to detect.


推荐阅读