如何在C中分配和释放对齐的内存

如何分配与C中特定边界对齐的内存(例如,缓存行边界)? 我正在寻找malloc / free类似的实现,理想情况下尽可能便携 – 至少在32位和64位架构之间。

编辑添加:换句话说,我正在寻找一些表现得像(现在过时的?) memalign函数的东西,它可以免费使用。

这是一个解决方案,它封装对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]); } 

使用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) 

posix_memalignmemalign的标准替代品,正如您所提到的那样已经过时了。

你用的是什么编译器? 如果您使用的是MSVC,则可以尝试使用_aligned_malloc()_aligned_free()