Search code examples
c++cposixmemory-alignmentdynamic-allocation

Allocating initialized, aligned memory


I'm writing a program (in C++) in which I need to allocate arrays whose starting addresses should be aligned with the cache line size. When I allocate these arrays I also want the memory initialized to zero.

Right now I have it working using the posix_memalign function. This works well for getting memory aligned arrays but the arrays are uninitilized. Is there a better function I can use to zero out the arrays when I initialize them or do I just have to settle for writing a separate loop to do it for me?


Solution

  • Just call memset on the block. Make sure you don't cast the pointer to a type that's expensive to set (like char *) before calling memset. Since your pointer will be aligned, make sure that information isn't hidden from the compiler.

    Update: To clarify my point about not hiding alignment, compare:

    char* mem_demo_1(char *j)
    { // *BAD* compiler cannot tell pointer alignment, must test
        memset(j, 0, 64);
        return j;
    }
    
    char* mem_demo_2(void)
    { // *GOOD* compiler can tell pointer alignment
        char * j = malloc(64);
        memset(j, 0, 64);
        return j;
    }
    

    With GCC, mem_demo_1 compiles to 60 lines of assembly while mem_demo_2 compiles to 20. The performance difference is also huge.