2

How would one go about using malloc (or new, since on most implementations new is implemented with malloc, not sure what the standard says about alignment and new other than data has to be aligned with the highest scalar alignment) with a type that has an alignment requirement set to being higher than the maximum alignment requirement on the system (alignof(std::max_align_t))? So something like

alignas(alignof(std::max_align_t) + alignof(int)) struct Something {
    ...
};
Curious
  • 20,870
  • 8
  • 61
  • 146
  • Let `n` denote the required alignment (too bad you haven't mentioned that in the question; would have made it easier to answer it). Just call `malloc` with `n+sizeof(struct Something)`, then search for an aligned address starting from the value returned by `malloc`. You are guaranteed to find such valid address between `[retVal,retVal+n-1]`. Then use that as the base address for your structure. – barak manos Feb 09 '17 at 16:01
  • @barakmanos That is a clever hack lol, there is no library solution to this? I guess C didn't have to worry about this since there was no alignment requirement higher than the maximum scalar requirement – Curious Feb 09 '17 at 16:05
  • I believe that any vendor must supply `malloc` which is suitable for the supported platform (compiler + underlying HW architecture). – barak manos Feb 09 '17 at 16:07
  • 1
    With C++11, you can use [aligned_alloc](http://en.cppreference.com/w/c/memory/aligned_alloc). Without C++11, In Visual Studio you can use [_aligned_malloc](https://msdn.microsoft.com/en-us/library/8z34s9c6.aspx) (but it's more C then C++). – Rotem Feb 09 '17 at 18:19

1 Answers1

0

Turning a comment into an answer.

Let ALIGNMENT denote the required alignment.

Then you can safely allocate your structure as follows:

char* buffer = new char[ALIGNMENT+sizeof(Something)];
uintptr_t address = reinterpret_cast<uintptr_t>(buffer);
uintptr_t aligned_address = address+ALIGNMENT-address%ALIGNMENT;
Something* something = reinterpret_cast<Something*>(aligned_address);
barak manos
  • 29,648
  • 10
  • 62
  • 114