How do you allocate memory that's aligned to a specific boundary in C (e.g., cache line boundary)? I'm looking for malloc/free like implementation that ideally would be as portable as possible --- at least between 32 and 64 bit architectures.
Edit to add: In other words, I'm looking for something that would behave like (the now obsolete?) memalign function, which can be freed using free.
Use
posix_memalign
/free
.posix_memalign
is a standard replacement formemalign
which, as you mention is obsolete.Here is a solution, which encapsulates the call to malloc, allocates a bigger buffer for alignment purpose, and stores the original allocated address just before the aligned buffer for a later call to free.
What compiler are you using? If you're on MSVC, you can try
_aligned_malloc()
and_aligned_free()
.