Does calling memcpy
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?
This should be similar for both c/cpp languages but I'm providing an example in cpp -
#include <iostream>
#include <cstring>
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 << tmp.ba << tmp.bb << "\n";
// everything is fine yet
A obj;
memcpy(&obj, &tmp, sizeof(tmp));
// 1. is this valid?
cout << obj.a << "\n";
B newB;
memcpy(&newB, &obj, sizeof(newB));
// 2. Are these valid?
cout << newB.ba << newB.bb << "\n";
}
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?
The structure and other functions related to it are in C library but we'll use and compile it with c++.