title: Dynamically allocate properly-aligned memory: is the new-expression on char arrays suitable?
body: <p>I am following Stefanus Du Toit's <em>hourglass</em> pattern, that is, implementing a C API in C++ and then wrapping it in C++ again. This is very similar to the <em>pimpl</em> idiom, and it is also transparent to the user, but prevents more ABI-related issues and allows for a wider range of foreign language bindings.</p>
  
  <p>As in the <em>pointer-to-implementation</em> approach, the underlying object's size and layout is not known by the outsiders at compile-time, so the memory in which it resides has to be dynamically allocated (<a href="https://stackoverflow.com/questions/4921932/pimpl-idiom-without-using-dynamic-memory-allocation"><em>mostly</em></a>). However, unlike in the <em>pimpl</em> case, in which the object has been fully defined at the allocation point, here its properties are completely hidden behind an opaque pointer.</p>
  
  <p>Memory obtained with <a href="http://en.cppreference.com/w/cpp/memory/c/malloc" rel="nofollow noreferrer"><code>std::malloc</code></a> is "<em>suitably aligned for any scalar type</em>", which makes it unsuitable for the task. I'm not sure about the <a href="http://en.cppreference.com/w/cpp/language/new" rel="nofollow noreferrer">new-expression</a>. Quoted from the section <a href="http://en.cppreference.com/w/cpp/language/new#Allocation" rel="nofollow noreferrer"><em>Allocation</em></a> of the linked page:</p>
  
  <blockquote>
    <p>In addition, if the new-expression is used to allocate an array of
    char or an array unsigned char, it may request additional memory from
    the allocation function if necessary to guarantee correct alignment of
    objects of all types no larger than the requested array size, if one
    is later placed into the allocated array.</p>
  </blockquote>
  
  <p>Does this mean that the following code is compliant?</p>
  
  <h2>C API</h2>
  
  <pre><code>size_t object_size      ( void );     // return sizeof(internal_object);
  size_t object_alignment ( void );     // return alignof(internal_object);
  void   object_construct ( void * p ); // new (p) internal_object();
  void   object_destruct  ( void * p ); // static_cast&lt;internal_object *&gt;(p)-&gt;~internal_object();
  </code></pre>
  
  <h2>C++ wrapper</h2>
  
  <pre><code>/* The memory block that p points to is correctly aligned
     for objects of all types no larger than object_size() */
  auto p = new char[ object_size() ];
  object_construct( p );
  object_destruct( p );
  delete[] p;
  </code></pre>
  
  <p>If it is not, how to dynamically allocate properly-aligned memory?</p>