title: Variable-length strings in structures and undefined behavior causing time travel
body: <p>In <a href="https://stackoverflow.com/questions/24527401/undefined-behavior-causing-time-travel/">this Stackoverflow question</a> or in the article <a href="http://blogs.msdn.com/b/oldnewthing/archive/2014/06/27/10537746.aspx" rel="nofollow noreferrer">Undefined behavior can result in time travel (among other things, but time travel is the funkiest)</a> one may learn that accessing data structures at indexes greater than their size is <em>undefined behavior</em>, and when a compiler sees <em>undefined behavior</em>, it generates crazy code without even reporting that  <em>undefined behavior</em> was encountered. This is done to make code run a few nanoseconds faster and because the standard permits it. So-called "time travel" appears because the compiler operates on control-flow branches, and when it sees <em>undefined behavior</em> in a branch, it just deletes that branch (on the basis that any behavior will do in place of <em>undefined behavior</em>).</p>
  
  <p>Nevertheless, here is an old idiom:</p>
  
  <pre><code>struct myString {
      int length;
      char text[1];
  }
  </code></pre>
  
  <p>used as</p>
  
  <pre><code>    char* s = "hello, world";
      int len = strlen(s);
      myString* m = malloc(sizeof(myString) + len);
      m-&gt;length = len;
      strcpy(&amp;m-&gt;text,s);
  </code></pre>
  
  <p>and now, what will happen if I access <code>m-&gt;text[3]</code>? (Note how it is declared.) Will the compiler take it as <em>undefined behavior</em>? If yes, how do I add an array of statically unknown amount of items to the end of a structure?</p>
  
  <p>In particular, I am interested in an array whose size is at least 1, but maybe more. Sort of,</p>
  
  <pre><code>struct x {
      unsigned u[1];
  };
  
  and access like `struct x* p; ... p-&gt;x[3]`.
  </code></pre>
  
  <p>UPD related: <a href="https://stackoverflow.com/questions/3711233/is-the-struct-hack-technically-undefined-behavior">Is the &quot;struct hack&quot; technically undefined behavior?</a> (as @mafso has noted in a comment).</p>