title: What precautions should I take to make a memory pool that does not invoke undefined behavior?
body: <p>My initial problem is that I have, on a project, several objects which share a lifetime (i.e., once I free one of them, I'll free them all), then I wanted to allocate a single block of memory. I have arrays of three different object types, <code>struct foo</code>, <code>void *</code>, and <code>char</code>. At first I wanted to <code>malloc()</code> a block like this:</p>
  
  <pre><code>// +---------------+---------+-----------+---------+---------+
  // | struct foo[n] | padding | void *[m] | padding | char[o] |
  // +---------------+---------+-----------+---------+---------+
  </code></pre>
  
  <p>But then... how could I accomplish this without invoking undefined behavior? I.e., respecting type aliasing rules, aligment... How to properly calculate the memory block size, declare the memory block (with its effective type), and how to properly get pointers to all three sections within it portably?</p>
  
  <p>(I do understand I could <code>malloc()</code> 3 blocks, which would result in three <code>free()</code>, but I'd like to know how to do it with a single block while still well-behaved.)</p>
  
  <p>I'd like to extend my problem to a more general question: what precautions should one take to implement a <a href="https://en.wikipedia.org/wiki/Memory_pool">memory pool</a> for objects with arbitrary sizes and alignment while keeping the program well-behaved? (<em>Assuming it is possible to implement it without invoking undefined behavior</em>.)</p>