title: C++ char array null terminator location
body: <p>I am a student learning C++, and I am trying to understand how null-terminated character arrays work. Suppose I define a char array like so:</p>
  
  <pre><code>char* str1 = "hello world";
  </code></pre>
  
  <p>As expected, <code>strlen(str1)</code> is equal to 11, and it is null-terminated.</p>
  
  <p>Where does C++ put the null terminator, if all 11 elements of the above char array are filled with the characters "hello world"? Is it actually allocating an array of length 12 instead of 11, with the 12th character being <code>'\0'</code>? <a href="http://www.cplusplus.com/doc/tutorial/ntcs/">CPlusPlus.com</a> seems to suggest that one of the 11 would need to be <code>'\0'</code>, unless it is indeed allocating 12.</p>
  
  <p>Suppose I do the following:</p>
  
  <pre><code>// Create a new char array
  char* str2 = (char*) malloc( strlen(str1) );
  
  // Copy the first one to the second one
  strncpy( str2, str1, strlen(str1) );
  
  // Output the second one
  cout &lt;&lt; "Str2: " &lt;&lt; str2 &lt;&lt; endl;
  </code></pre>
  
  <p>This outputs <code>Str2: hello worldatcomY╗°g♠↕</code>, which I assume is C++ reading the memory at the location pointed to by the pointer <code>char* str2</code> until it encounters what it interprets to be a null character.</p>
  
  <p>However, if I then do this:</p>
  
  <pre><code>// Null-terminate the second one
  str2[strlen(str1)] = '\0';
  
  // Output the second one again
  cout &lt;&lt; "Terminated Str2: " &lt;&lt; str2 &lt;&lt; endl;
  </code></pre>
  
  <p>It outputs <code>Terminated Str2: hello world</code> as expected.</p>
  
  <p>But doesn't writing to <code>str2[11]</code> imply that we are writing outside of the allocated memory space of <code>str2</code>, since <code>str2[11]</code> is the 12th byte, but we only allocated 11 bytes? </p>
  
  <p>Running this code does not seem to cause any compiler warnings or run-time errors. Is this safe to do in practice? Would it be better to use <code>malloc( strlen(str1) + 1 )</code> instead of <code>malloc( strlen(str1) )</code>?</p>