你如何分配该真实对准到特定的边界在C(例如,高速缓存行边界)存储器?我正在寻找的malloc /免费等实现,理想地将尽可能便携式---至少32位和64位体系结构之间。

编辑补充:换句话说,我正在寻找的东西会表现得像的包括memalign 功能,其可以使用自由释放。

有帮助吗?

解决方案

下面是一个解决方案,它封装在调用malloc的,分配用于对准目的的更大的缓冲和存储只为以后的呼叫对齐缓冲器之前的原始分配地址,以释放

// 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()

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top