title: Can I "over-extend" an array by allocating more space to the enclosing struct?
body: <p>Frankly, is such a code valid or does it produce UB?</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;string.h&gt;
  
  struct __attribute__((__packed__)) weird_struct
  {
      int some;
      unsigned char value[1];
  };
  
  int main(void)
  {
      unsigned char text[] = "Allie has a cat";
      struct weird_struct *ws =
          malloc(sizeof(struct weird_struct) + sizeof(text) - 1);
      ws-&gt;some = 5;
      strcpy(ws-&gt;value, text);
      printf("some = %d, value = %s\n", ws-&gt;some, ws-&gt;value);
      free(ws);
      return 0;
  }
  </code></pre>
  
  <p><a href="http://ideone.com/lpByQD" rel="noreferrer">http://ideone.com/lpByQD</a></p>
  
  <p>I’d never think it is valid to something like this, but it would seem that SystemV message queues do exactly that: <a href="https://linux.die.net/man/2/msgop" rel="noreferrer">see the man page</a>.</p>
  
  <p>So, if SysV msg queues can do that, perhaps I can do this too? I think I’d find this useful to send data over the network (hence the <code>__attribute__((__packed__))</code>).</p>
  
  <p>Or, perhaps this is a specific guarantee of SysV msg queues and I shouldn’t do something like that elsewhere? Or, perhaps this technique can be employed, only I do it wrongly? I figured out I’d better ask.</p>
  
  <p>This <code>- 1</code> in <code>malloc(sizeof(struct weird_struct) + sizeof(text) - 1)</code> is because I take into account that one byte is allocated anyway thanks to <code>unsigned char value[1]</code> so I can subtract it from <code>sizeof(text)</code>.</p>