title: Why does initializing a string member of a zeroed struct with "" cause a crash but not if the string has length of 1 or greater?
body: <p>I am using g++ with the c++ 17 standard</p>
  <p>In the accepted answer for question <a href="https://stackoverflow.com/questions/1998752/memset-or-value-initialization-to-zero-out-a-struct">memset() or value initialization to zero out a struct?</a> it states that</p>
  <pre class="lang-cpp prettyprint-override"><code>struct TestStruct
  {
      int a;
      std::string b;
  };
  
  TestStruct t = {};  // OK
  
  {
      TestStruct t1;
      memset(&amp;t1, 0, sizeof t1);  // ruins member 'b' of our struct
  }  // Application crashes here
  </code></pre>
  <p>whereas in my own testing the program does not crash at this point.</p>
  <p>Example A:</p>
  <pre class="lang-cpp prettyprint-override"><code>struct TestStruct
  {
    int a;
    std::string b;
  };
  
  TestStruct t1;
  memset(&amp;t1, 0, sizeof t1);
  
  t1.b = &quot;before&quot;;
  std::cout &lt;&lt; t1.b &lt;&lt; std::endl;
  std::cout &lt;&lt; &quot;after&quot;;
  </code></pre>
  <p>This prints</p>
  <p>before</p>
  <p>after</p>
  <p>Example B:</p>
  <pre class="lang-cpp prettyprint-override"><code>struct TestStruct
  {
    int a;
    std::string b;
  };
  
  TestStruct t1;
  memset(&amp;t1, 0, sizeof t1);
  
  t1.b = &quot;&quot;;
  std::cout &lt;&lt; t1.b &lt;&lt; std::endl;
  std::cout &lt;&lt; &quot;after&quot;;
  </code></pre>
  <p>This prints nothing as the program crashes directly after
  t1.b = &quot;&quot;;</p>
  <p>For the sake of thoroughness I also tested with t1 going out of scope as in the referenced question</p>
  <pre class="lang-cpp prettyprint-override"><code>struct TestStruct
  {
    int a;
    std::string b;
  };
  
  {
    TestStruct t1;
    memset(&amp;t1, 0, sizeof t1);
  
    t1.b = &quot;before&quot;;
    std::cout &lt;&lt; t1.b &lt;&lt; std::endl;
    std::cout &lt;&lt; &quot;after&quot; &lt;&lt; std::endl;
  }
  std::cout &lt;&lt; &quot;eventually&quot;;
  </code></pre>
  <p>prints</p>
  <p>before</p>
  <p>after</p>
  <p>eventually</p>
  <p>My main question is, why does example B crash where example A does not?</p>