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?
Just call
memseton the block. Make sure you don’t cast the pointer to a type that’s expensive to set (likechar *) before callingmemset. 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:
With
GCC,mem_demo_1compiles to 60 lines of assembly whilemem_demo_2compiles to 20. The performance difference is also huge.