aligned malloc() in GCC?

Viewed 79949

Is there any standardized function in GCC or glibc to allocate memory block at aligned pointer? Like _align_malloc() in MSVC?

6 Answers

Since C++17 there is standard library function std::aligned_alloc() with signature:

void* aligned_alloc( std::size_t alignment, std::size_t size );

You must #include <cstdlib> to use it. The size parameter must be a multiple of alignment. On failure returns null pointer. Allocated pointer is freed using std::free().

Although not all compilers may have implemented this standard function. For example MSVC didn't implement it for next reason (read here):

MSVC doesn't support the aligned_alloc function. C11 specified aligned_alloc() in a way that's incompatible with the Microsoft implementation of free(), namely, that free() must be able to handle highly aligned allocations.

For MSVC _aligned_malloc() and _aligned_free() must be used.

But GCC/G++ has this standard std::aligned_alloc(), at least I tested this on Windows+Cygwin.

Related