Reputation: 321
Given the three following structures (in any architecture of 16 bits or above) :
typedef struct {
int a;
char b;
float c;
char d;
int e[10];
} StructA;
typedef struct {
int a;
char b;
float c;
char d;
} StructB;
typedef struct {
StructB sb;
int e[10];
} StructC;
Then I declare :
StructA sa;
StructC sc;
Let's assume the impossible fact that sa and sc point to the same address for comparison purpose.
What I understood is that sa, sa.a, sc, sc.sb and sc.sb.a would share the same address given the (impossible) above condition.
My question is : Given sa and sc start at the same address, can I take for granted that sa.e and sc.e also start at the same address given a struct is contiguous in memory (but padding) ? Can padding get in the way of my guess ? Would using memcpy on sa into sc be valid ?
Upvotes: 2
Views: 72
Reputation: 214365
The C memory model is somewhat high-level and assumes that all objects (variables) in memory have a type, called effective type. If you somehow manage to allocate sa
and sc
on the same address through some linker tricks, you are doing things beyond the scope of the C language. And so no behavior is guaranteed, it could confuse the compiler and it is undefined behavior.
Had you allocated two structs at the same address by using union
, it would be another story. In such a case each individual struct will still use padding however, so there's no guarantees unless you know for sure how each struct is padded. If each struct was member of the same union, you could safely memcpy between them using sizeof
the union, even if one union member is smaller than the other.
Upvotes: 1