1

I'm writing some SIMD code. I'll need my arrays to be aligned to 32bytes with an option to upgrade to 64byte if I ever decide to target a CPU that supports 512bit simd instructions.

From what I can tell realloc doesn't seem to keep any promises about the alignment. It seems malloc and realloc will only guarantee 8bytes/64bits?

Without writing my own what are my options if I want to reallocate a piece of memory?

Eric Stotch
  • 141
  • 4
  • 19
  • Does [alignas](https://en.cppreference.com/w/cpp/language/alignas) work? – Eljay May 03 '20 at 19:12
  • @Eljay: The `alignas` specifier only applies to variable declarations, but the OP is asking about dynamic memory allocation using `malloc`/`realloc`. Therefore, it will not work. – Andreas Wenzel May 03 '20 at 20:39
  • 1
    It appears that you need to use the function [`aligned_malloc`](https://en.cppreference.com/w/c/memory/aligned_alloc). However, the linked documentation does not state whether the alignment is guaranteed to be preserved by [`realloc`](https://en.cppreference.com/w/c/memory/realloc). – Andreas Wenzel May 03 '20 at 20:50
  • If you are using the Microsoft Windows platform, you can use [`_aligned_realloc`](https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/aligned-realloc). – Andreas Wenzel May 03 '20 at 21:10
  • Related question: [Is there really no version of realloc() supporting alignment](https://stackoverflow.com/questions/45503469/is-there-really-no-version-of-realloc-supporting-alignment)? – Andreas Wenzel May 03 '20 at 21:24

1 Answers1

0

There is std::align which can be used to acquire a pointer to an aligned region of memory. You can check whether the reallocated region is still aligned by comparing the pointer with the result of std::align. If not, a memmove() might be neccessary.

There is also std::aligned_storage which might be an option for aligned allocations of a fixed (i.e compile-time) legnth.


A possible implementation strategy could be an allocator which retrieves memory from a specific memory pool. The memory pool only returns memory aligned by std::align or could manage blocks of std::aligned_storage. This approach also gives you all the advantages of memory pools, e.g cache locality, no memory fragmentation and perhaps faster allocation algorithms (depends on your pools implementation and that of malloc).

Sebastian Hoffmann
  • 2,815
  • 1
  • 12
  • 22