0

In my program I initialize a series of buffers, and all but one of those buffers is initialized with calloc because the buffers must be initialized to zero.

But calloc doesn't give me 64-byte aligned buffers by default, so I want to switch to posix_memalign. However, posix_memalign doesn't initialize to zero.

So my question is: how can I initialize an aligned memory buffer to zero (with posix_memalign or anything else)?

RTC222
  • 2,025
  • 1
  • 20
  • 53
  • 3
    Did you consider memset? – prl Jun 27 '20 at 20:40
  • No but that sounds like a good way to do it because these buffers are small, and memset is probably the fastest way to do it. I'll try that now. – RTC222 Jun 27 '20 at 20:47
  • 1
    Unfortunately POSIX (and glibc) don't bother to provide aligned allocators that can take advantage of getting a zeroed page from the OS (and defer lazy allocation). If you want that efficiency, you'd have to write your own allocator around mmap, or around `calloc`. This is one area where Windows has a better library API, providing functions including aligned_calloc. – Peter Cordes Jun 27 '20 at 20:52
  • Just to follow up, memset does the job. If these buffers were very large then a strategy like suggested by @Peter Cordes could be useful for efficiency. However, buffers are allocated only once so it would have to be a significant improvement in speed over memset. – RTC222 Jun 27 '20 at 21:33
  • Big improvement would only be likely if some pages sometimes went entirely unwritten and could just read as zero, getting cache hits from the same shared page of zeros. For small buffers it's not a big waste to store zeros; OoO exec + store buffer can absorb those writes without stalling. BTW, `aligned_alloc` is a nicer interface than `posix_memalign`; it returns a pointer instead of taking a pointer-to-a-pointer. That can sometimes defeat escape analysis for aliasing, preventing some optimizations if you had an array of pointers. – Peter Cordes Jun 27 '20 at 21:57

0 Answers0