我找到了描述自定义内存分配器工作原理的链接:
https://github.com/lovelaced/muhalloc/blob/master/mem.c
为什么 Mem_Alloc()
除以 4 并将 size
增加为 4 的倍数?
这是来自该链接的功能描述:
/* Function for allocating 'size' bytes. */
/* Returns address of allocated block on success */
/* Returns NULL on failure */
/* Here is what this function should accomplish */
/* - Check for sanity of size - Return NULL when appropriate */
/* - Round up size to a multiple of 4 */
/* - Traverse the list of blocks and allocate the best free block which can accommodate the requested size */
/* -- Also, when allocating a block - split it into two blocks when possible */
/* Tips: Be careful with pointer arithmetic */
void* Mem_Alloc(int size)
...
最佳答案
用于对齐;并且是如何做到这一点的一个非常糟糕的例子。如果您查看 K&R 的 C 编程语言中的示例,它会向可移植、有效且易于理解的分配器提供源代码。 C是一门微妙的语言,最好先从阅读好的程序中学习。
关于c 中的自定义内存分配器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55272778/