c - 使用 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 字节中存储我想要的任何内容。这是不好的做法吗?仅使用数组来增加结构的大小似乎很奇怪。
解决方案
It is okay to allocate all the memory your application needs during initialization if:
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)
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:
For sure you have to implement your own mp_free call to return the freed block back to the memory pool.
If your application frees a block in the middle of the list, your mp_malloc should be able to reuse it.
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.
推荐阅读
- bash - docker pull - Azure DevOps 中的无效参考格式
- python-2.7 - python2.7的dict.items()函数如何改变序列的顺序?
- javascript - 如何修复 - 我是初学者和
- mysql - 为排除某些数据创建 SQL
- reactjs - ts/react - useEffect 中的 fetch 被多次调用
- git - 加密/解密 Git 存储库的选项?
- anaconda - anaconda:无法使用 shell 脚本切换环境
- python - 使用来自 csv Python 的数据更新 Firebird 表
- java - 让 git 忽略连续的换行符
- kubernetes - kops 导出 kubeconfig,TTL 不会减少