How to allocate and free aligned memory in C

后端 未结 3 1157
醉酒成梦
醉酒成梦 2021-01-30 07:15

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 po

相关标签:
3条回答
  • 2021-01-30 07:51

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

    0 讨论(0)
  • 2021-01-30 07:56

    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]);
    }
    
    0 讨论(0)
  • 2021-01-30 08:06

    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.

    0 讨论(0)
提交回复
热议问题