malloc and mallocArray ignore Storable alignment requirements
Not sure if this is a bug or a feature request:
allocaBytesAligned exists and allocates a new pinned byte array with a given alignment. It is used for both
However, we don't currently have such a facility with
mallocArray currently just invoke
mallocBytes requests memory without alignment guarantees, so the resulting memory might well violate required
alignment for the result.
We don't currently pad things out or get properly aligned memory.
It strikes me that we should in theory add
mallocBytesAligned, and switch
mallocArray to invoke it instead of
Foreign.Marshal.Alloc.mallocBytes just invokes system
malloc, so it seems that
posix_memalign would be suitable.
_malloc on the system is probably aligning to a pretty common unit size, but if you start doing SIMD stuff you'll start seeing 16 byte alignment requirements, folks who care about cache architecture for example can have 128 byte alignments to pad things to separate cache lines.
We probably haven't noticed since you likely get back bytes with slot-sized alignment just by construction, so if your alignment requirements stay in the <= 8 range you'll be okay, but for larger alignments it appears you'd just get wrong answers.
If something more subtle is going on here (e.g. an
alignment bigger than some threshold wont be respected or that users should explicitly expect
mallocArray to silently allocate an array with the wrong alignment) that I missed then we definitely need better documentation to address the issue.