c中的自定义内存分配器

时间:2019-03-21 02:06:23

标签: c memory-management operating-system heap-memory

我发现此链接描述了自定义内存分配器的工作方式:

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)
    ...

2 个答案:

答案 0 :(得分:1)

用于对齐;这是一个非常糟糕的示例。如果看一下K&R的C编程语言中的示例,它会将源代码提供给可移植,有效且易于理解的分配器。 C是一种微妙的语言,最好先从阅读好的程序中学习。

答案 1 :(得分:1)

数据对齐,以提高访问内存的效率

假定处理器始终从内存中提取4个字节,其地址必须是4的倍数,然后可以通过单个内存操作来读取或写入该值。否则,我们可能需要执行两次内存访问,因为对象可能会拆分为两个4字节内存块。