title: Does memcpy preserve data between different types?
body: <p>Does calling <code>memcpy</code> on two different structures preserve the original data if the buffer size is sufficient? And is it defined to retrieve values of another data type with data of previous data type if their respective data types overlap?</p>
  
  <p>This should be similar for both c/cpp languages but I'm providing an example in cpp -</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;cstring&gt;
  
  using namespace std;
  
  struct A{
    int a;
    char b[10];
  };
  
  struct B{
    int ba;
    int bb;
  };
  
  int main(){
      B tmp;
      tmp.ba = 50;
      tmp.bb = 24;
      cout &lt;&lt; tmp.ba &lt;&lt; tmp.bb &lt;&lt; "\n";
  
      // everything is fine yet
  
      A obj;
      memcpy(&amp;obj, &amp;tmp, sizeof(tmp));
  
      // 1. is this valid?
      cout &lt;&lt; obj.a &lt;&lt; "\n";
  
      B newB;
      memcpy(&amp;newB, &amp;obj, sizeof(newB));
  
      // 2. Are these valid?
      cout &lt;&lt; newB.ba &lt;&lt; newB.bb &lt;&lt; "\n";
  }
  </code></pre>
  
  <p>In above example I've commented 1st and 2nd comment, are they valid and is data preserved if sufficient buffer area is provided? Can we do this portably?</p>
  
  <p>The structure and other functions related to it are in C library but we'll use and compile it with c++.</p>