How to allocate and free aligned memory in C

让人想犯罪 __ 提交于 2019-12-20 08:40:00

问题


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.

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.


回答1:


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**)((uintptr_t)(mem+ALIGN+sizeof(void*)) & ~(ALIGN-1));
    ptr[-1] = mem;
    return ptr;
}

void aligned_free(void *ptr) {
    free(((void**)ptr)[-1]);
}



回答2:


Use 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_memalign is a standard replacement for memalign which, as you mention is obsolete.




回答3:


What compiler are you using? If you're on MSVC, you can try _aligned_malloc() and _aligned_free().



来源:https://stackoverflow.com/questions/1919183/how-to-allocate-and-free-aligned-memory-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!