Aligned memory management?

后端 未结 7 1893
清歌不尽
清歌不尽 2020-12-13 05:00

I have a few related questions about managing aligned memory blocks. Cross-platform answers would be ideal. However, as I\'m pretty sure a cross-platform solution does not

7条回答
  •  情书的邮戳
    2020-12-13 05:28

    Starting a C11, you have void *aligned_alloc( size_t alignment, size_t size ); primitives, where the parameters are:

    alignment - specifies the alignment. Must be a valid alignment supported by the implementation. size - number of bytes to allocate. An integral multiple of alignment

    Return value

    On success, returns the pointer to the beginning of newly allocated memory. The returned pointer must be deallocated with free() or realloc().

    On failure, returns a null pointer.

    Example:

    #include 
    #include 
    
    
        int main(void)
        {
            int *p1 = malloc(10*sizeof *p1);
            printf("default-aligned addr:   %p\n", (void*)p1);
            free(p1);
    
            int *p2 = aligned_alloc(1024, 1024*sizeof *p2);
            printf("1024-byte aligned addr: %p\n", (void*)p2);
            free(p2);
        }
    

    Possible output:

    default-aligned addr:   0x1e40c20
    1024-byte aligned addr: 0x1e41000
    

提交回复
热议问题