c中的自定义内存分配器

问题描述 投票:1回答:2

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

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)
    ...
c memory-management operating-system heap-memory
2个回答
1
投票

数据对齐,用于访问内存效率

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


2
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.