title: Overflowing char array overwrites the exact same string every time - why?
body: <p>I have the following code that shows the dangers of using char arrays over strings:</p>
  
  <pre><code>int main(){
      char password[] = "SECRET";
      char msg[10], ch;
      int i = 0;
  
      cout &lt;&lt; "Please enter your name:";
      while((ch = getchar()) != '\n'){
              msg[i++] = ch;
      }
      msg[i] = '\0';
  
      cout &lt;&lt; "\n\nHello " &lt;&lt; msg &lt;&lt; endl;
      cout &lt;&lt; "The password is " &lt;&lt; password;
  }
  </code></pre>
  
  <p>When I enter a name (stored in <code>char msg[10]</code>) that is <strong>longer than 16 characters</strong>, everything after those 16 characters replaces the value stored in <code>char password[]</code> ("SECRET").</p>
  
  <ol>
  <li>Why is this the case? (<em>a general curiosity</em>)</li>
  <li>Why 16 characters and not 10 - the size of the array?</li>
  <li>Why is it always <code>password</code> that gets overwritten and not some other variable or some other part of the memory where I wouldn't notice immediately?</li>
  <li>What's the benefit of using char[] over strings then?</li>
  </ol>
  
  <p>EDIT: Updated with follow up questions:<br>
   <strong>5.</strong> In response to the argument that <code>password</code> and <code>msg</code> are declared next to each other, I shuffled the declaration block as follows:</p>
  
  <pre><code>char password[] = "SECRET";
  char ch;
  int i = 0;
  char msg[10];
  </code></pre>
  
  <p>However, no change.<br>
   <strong>6.</strong> In response to the argument that it was chance that caused the gap between <code>msg</code> and <code>password</code> to be 6 (bytes?) long, I have recompiled the code many times, including the reshuffling above. Still, no change.
  <br><br>Any suggestions as to why?</p>