问题描述
我需要分配应该与页面大小对齐的内存.我需要将此内存传递给ASM
代码,该代码计算所有数据块的异或.我需要使用malloc()
来完成此操作.
I need to allocate memory which should be page size aligned. I need to pass this memory to an ASM
code which calculates xor of all data blocks. I need to do this with malloc()
.
推荐答案
您应该使用此功能.
如果由于某种原因不能这样做,那么通常的方法是将块大小添加到分配大小中,然后使用整数算术欺骗指针.
If you can't, for whatever reason, then the way this is generally done is by adding the block size to the allocation size, then using integer-math trickery to round the pointer.
类似这样的东西:
/* 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);
}
这还没有经过非常深入的测试,但是您知道了.
This has not been very deeply tested but you get the idea.
请注意,以后不可能找到指向free()
内存的正确指针.要解决此问题,我们必须添加一些其他机制:
Note that it becomes impossible to figure out the proper pointer to free()
the memory later. To fix that, we would have to add some additional machinery:
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
指针才能获得正确对齐的指针.
This wraps the pointer trickery a bit, and gives you a pointer you can free()
, but you need to dereference into the aligned
pointer to get the properly aligned pointer.
这篇关于如何分配与页面大小对齐的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!