我需要分配应该与页面大小对齐的内存。我需要将此内存传递给计算所有数据 block 的异或的 ASM
代码。我需要用 malloc()
来做到这一点。
最佳答案
有一些你应该使用的函数。
如果你不能,无论出于何种原因,通常这样做的方法是将 block 大小添加到分配大小,然后使用整数数学技巧来舍入指针。
类似这样的:
/* Note that alignment must be a power of two. */
void * allocate_aligned(size_t size, size_t alignment)
{
const size_t mask = alignment - 1;
const uintptr_t mem = (uintptr_t) malloc(size + alignment);
return (void *) ((mem + mask) & ~mask);
}
这还没有经过非常深入的测试,但你明白了。
请注意,以后不可能找出指向 free()
内存的正确指针。为了解决这个问题,我们必须添加一些额外的机制:
typedef struct {
void *aligned;
} AlignedMemory;
AlignedMemory * allocate_aligned2(size_t size, size_t alignment)
{
const size_t mask = alignment - 1;
AlignedMemory *am = malloc(sizeof *am + size + alignment);
am->aligned = (void *) ((((uintptr_t) (am + 1)) + mask) & ~mask);
return am;
}
这稍微包装了指针技巧,并为您提供了一个可以free()
的指针,但是您需要取消引用到aligned
指针以获得正确对齐指针。
关于c - 如何分配页面大小对齐的内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21550420/