2

I'm building a portable arena allocator for embedded systems.
Like for malloc, one of the requirements is to return a pointer aligned with the memory.

The question is: Is there a way to know at compile time what are the memory alignment requirements for a given platform in C?

I've seen this code snippets floating around, but I haven't find any documentation to support it's validity:

#ifndef DEFAULT_ALIGNMENT
   #define DEFAULT_ALIGNMENT (2*sizeof(void *))
#endif
gbt
  • 671
  • 6
  • 17

1 Answers1

4

malloc is required to return a pointer properly aligned to hold an object of any type. Which means it must be aligned at least as the largest scalar type. Luckily C is defining such a type as max_align_t. In the C11 standard (draft) section 6.2.8 it says:

A fundamental alignment is represented by an alignment less than or equal to the greatest alignment supported by the implementation in all contexts, which is equal to _Alignof (max_align_t).

Test it out:

#include <stdio.h>
#include <stddef.h> // <- this required for max_align_t

int main(void) {
    printf("%zu\n",  _Alignof (max_align_t));
    return 0;
}

Demo: https://ideone.com/cDSVtH

Eugene Sh.
  • 9,986
  • 2
  • 26
  • 41