你怎么分配多数民众赞成对齐到特定边界C(例如,高速缓存行边界)的内存?我正在寻找的malloc /免费的像实施,理想将尽可能实现可移植性---至少在32位和64位架构。
How do you allocate memory that's aligned to a specific boundary in C (e.g., cache line boundary)? I'm looking for malloc/free like implementation that ideally would be as portable as possible --- at least between 32 and 64 bit architectures.
编辑补充:换句话说,我在寻找的东西会表现得像是的 memalign可功能,可以使用免费的释放。
Edit to add: In other words, I'm looking for something that would behave like (the now obsolete?) memalign function, which can be freed using free.
推荐答案
下面是一个解决方案,它封装在调用malloc的,分配的调整目的更大的缓冲区,只为一对准缓冲区之前存储原始分配的地址后来打电话来释放。
Here is a solution, which encapsulates the call to malloc, allocates a bigger buffer for alignment purpose, and stores the original allocated address just before the aligned buffer for a later call to free.
// cache line
#define ALIGN 64
void *aligned_malloc(int size) {
void *mem = malloc(size+ALIGN+sizeof(void*));
void **ptr = (void**)((long)(mem+ALIGN+sizeof(void*)) & ~(ALIGN-1));
ptr[-1] = mem;
return ptr;
}
void aligned_free(void *ptr) {
free(((void**)ptr)[-1]);
}
相关推荐
最新文章