Question: If we have two non-compatible structures or unions, but objects of both of the types have the same size of object representation would I get Undefined/Unspecified/Well-defined Behavior if I take object representation of some object of one of the types and "reinterpret" it as another type. (I do hope the wording is not weird).
My thoughts:
I mentioned the structure or union because N6.2.6.1(p6)
:
The value of a structure or union object is never a trap
Also I found that we can copy a value of an object into a char array 6.2.6.1(p4)
:
The value may be copied into an object of type
unsigned char [n]
(e.g., bymemcpy
); the resulting set of bytes is called the object representation of the value.
But the Standard does not specify that we can copy the object representation back. So I think it is UB to copy object representation back into an object of a type having representation of the same size (even if it's not a trap), but I'm not sure...
Example:
struct test1_t{
int a;
long b;
};
struct test2_t{
int c;
int d;
int e;
int f;
};
int main(){
struct test1_t t1 = {.a = 100, .b = 2000};
struct test2_t t2 = {.c = 1000, .d = 20000, .e = 300000, .f = 4000000};
size_t size;
if((size = sizeof(struct test1_t)) == sizeof(struct test2_t)){
char repr[size];
memcpy(&repr, &t2, size); // since value of structure or union
// is never a trap why don't we treat
// the representation as of some object
// of type struct test_t1
memcpy(&t1, &repr, size);
printf("t1.a = %d\n", t1.a); //t1.a = 1000
printf("t1.b = %d\n", t1.b); //t1.b = 300000
}
}
The result can be explained with padding in struct test1_t
after int a;
.