c 中的自定义内存分配器
Custom Memory Allocator in c
我发现这个 link 描述了自定义内存分配器的工作原理:
https://github.com/lovelaced/muhalloc/blob/master/mem.c
为什么Mem_Alloc()
除以4增加size
是4的倍数?
这是link中函数的描述:
/* 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语言是一门微妙的语言,最好先从阅读好的程序中学习。
数据对齐,为了访问内存效率
假设一个处理器总是从内存中获取 4 个字节,地址必须是 4 的倍数。然后可以通过单个内存操作读取或写入该值。否则,我们可能需要执行两次内存访问,因为对象可能被拆分为两个 4 字节的内存块。
我发现这个 link 描述了自定义内存分配器的工作原理:
https://github.com/lovelaced/muhalloc/blob/master/mem.c
为什么Mem_Alloc()
除以4增加size
是4的倍数?
这是link中函数的描述:
/* 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语言是一门微妙的语言,最好先从阅读好的程序中学习。
数据对齐,为了访问内存效率
假设一个处理器总是从内存中获取 4 个字节,地址必须是 4 的倍数。然后可以通过单个内存操作读取或写入该值。否则,我们可能需要执行两次内存访问,因为对象可能被拆分为两个 4 字节的内存块。