Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

aligned malloc() in GCC?

Tags:

c

malloc

gcc

People also ask

What is aligned malloc?

3.6 Allocating Aligned Memory Blocks. The address of a block returned by malloc or realloc in GNU systems is always a multiple of eight (or sixteen on 64-bit systems). If you need a block whose address is a multiple of a higher power of two than that, use aligned_alloc or posix_memalign .

Is malloc memory aligned?

Since malloc (or another dynamic memory allocator) is not necessarily guaranteed to align memory as we require, we'll need to perform two extra steps: Request extra bytes so we can returned an aligned address. Request extra bytes and store the offset between our original pointer and our aligned pointer.

Is malloc 16 byte aligned?

The GNU documentation states that malloc is aligned to 16 byte multiples on 64 bit systems.

What is Valloc?

The valloc() function has the same effect as malloc() , except that the allocated memory will be aligned to a multiple of the value returned by sysconf(_SC_PAGESIZE) . Note: When free() is used to release storage obtained by valloc() , the storage is not made available for reuse.


Since the question was asked, a new function was standardized by C11:

void *aligned_alloc(size_t alignment, size_t size);

and it is available in glibc (not on windows as far as I know). It takes its arguments in the same order as memalign, the reverse of Microsoft's _aligned_malloc, and uses the same free function as usual for deallocation.

A subtle difference is that aligned_alloc requires size to be a multiple of alignment.


See the memalign family of functions.


The [posix_memalign()][1] function provides aligned memory allocation and has been available since glibc 2.1.91.

But not necessarily with other compilers: quoting the standard "The posix_memalign() function is part of the Advisory Information option and need not be provided on all implementations."


There are _mm_malloc and _mm_free which are supported by most compilers of the x86/x64 world, with at least:

  • gcc
  • MinGW (gcc win32/win64)
  • MSVC
  • clang
  • ICC

AFAIK, these functions are not a standard at all. But it is to my knowledge the most supported ones. Other functions are more compiler specific:

  • _aligned_malloc is MSVC and MinGW only
  • posix memalign functions are not supported by at least MSVC

There are also C11 standard functions but unfortunately they are not in c++11, and including them in c++ require non standard preprocessor defines...


It depends on what kind of alignment you expect. Do you want a stricter alignment, or a more relaxed alignment?

malloc by definition is guaranteed to return a pointer that is properly aligned for storing any standard type in C program (and, therefore, any type built from standard types). Is it what your are looking for? Or do you need something different?