cpointersmemory-alignmentword-boundaries

Alignment of C structure


I have some binary data in a file and load the file into memory at char* data. Now I know e.g. that at offset 123 begins a struct something.

Is it safe to do the following

(struct something*) (data + 123) // ??&data [123]??

and then access members of the struct. Or should I do something like

struct something record;
memcpy (&record, data + 123, sizeof (struct something) );

Or even something completely different?

My question is mainly motivated, because I have some fuzzy recollections about "memory alignment", "word boundaries", etc...


Solution

  • Yes, you should use memcpy, not pointer conversion, for exactly the reason you discuss: alignment. Converting pointers is not safe. If the alignment is wrong, the behavior when you use the resulting pointer is not guaranteed by the C standard.

    An alternative in some situations is to read the data directly into the object.