How to align pointer

前端 未结 6 2364
说谎
说谎 2020-12-01 04:29

How do I align a pointer to a 16 byte boundary?

I found this code, not sure if its correct

char* p= malloc(1024);

if ((((unsigned long) p) % 16) !=          


        
6条回答
  •  日久生厌
    2020-12-01 05:22

    Try this:

    It returns aligned memory and frees the memory, with virtually no extra memory management overhead.

    #include 
    #include 
    
    size_t roundUp(size_t a, size_t b) { return (1 + (a - 1) / b) * b; }
    
    // we assume here that size_t and void* can be converted to each other
    void *malloc_aligned(size_t size, size_t align = sizeof(void*))
    {
        assert(align % sizeof(size_t) == 0);
        assert(sizeof(void*) == sizeof(size_t)); // not sure if needed, but whatever
    
        void *p = malloc(size + 2 * align);  // allocate with enough room to store the size
        if (p != NULL)
        {
            size_t base = (size_t)p;
            p = (char*)roundUp(base, align) + align;  // align & make room for storing the size
            ((size_t*)p)[-1] = (size_t)p - base;      // store the size before the block
        }
        return p;
    }
    
    void free_aligned(void *p) { free(p != NULL ? (char*)p - ((size_t*)p)[-1] : p); }
    

    Warning:

    I'm pretty sure I'm stepping on parts of the C standard here, but who cares. :P

提交回复
热议问题