fua*_*uad 22 c alignment memory-alignment memory-mapped-files
如何分配与C中特定边界对齐的内存(例如,缓存行边界)?我正在寻找malloc/free类似的实现,理想情况下尽可能便携 - 至少在32位和64位架构之间.
编辑添加:换句话说,我正在寻找一些表现得像(现在过时的?)memalign函数的东西,它可以免费使用.
Jer*_*ome 26
这是一个解决方案,它封装对malloc的调用,为对齐目的分配一个更大的缓冲区,并在对齐的缓冲区之前存储原始分配的地址,以便稍后调用free.
// cache line
#define ALIGN 64
void *aligned_malloc(int size) {
void *mem = malloc(size+ALIGN+sizeof(void*));
void **ptr = (void**)((uintptr_t)(mem+ALIGN+sizeof(void*)) & ~(ALIGN-1));
ptr[-1] = mem;
return ptr;
}
void aligned_free(void *ptr) {
free(((void**)ptr)[-1]);
}
Run Code Online (Sandbox Code Playgroud)
Luc*_*ncu 10
使用posix_memalign/ free.
int posix_memalign(void **memptr, size_t alignment, size_t size);
void* ptr;
int rc = posix_memalign(&ptr, alignment, size);
...
free(ptr)
Run Code Online (Sandbox Code Playgroud)
posix_memalign是一个标准的替代品memalign,正如你所提到的那样已经过时了.