I have data of a structure type in C:
typedef struct {
type0 field0;
type1 field1;
} foo_struct;
foo_struct foo;
Now let's say I have a buffer allocated in some fashion in virtual memory, of size sizeof(foo_struct)
char *buf = <some allocation method>
Then I copy the data from foo
to buf
, for example by memcpy
.
Then I want to access the fields in buf
like so:
((foo_struct *)buf)->fieldn
Is this guaranteed (by the C11 standard) to always work?
People in another question (on a different main topic)
, seem to be saying, yes this is guaranteed to work, especially provided that buf
is well-aligned, like, on a page boundary.
Yes it is practically assured. But I think, no matter how well it is "aligned", page boundary, or what not, there is no 100% guarantee by the standard. Is there?
It kind of depends on what
<some allocation method>
is. Here is what the standard [7.22.3] says about malloc :So according to the standard, you can do what you're asking when using malloc. Most other well written memory allocators should satisfy this requirement as well.