Alignment of C structure

91 views Asked by At

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...

2

There are 2 answers

3
Eric Postpischil On BEST ANSWER

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.

0
tristan On

It depends.

On some modern CPUs(like x86), it's OK to access unaligned word for read/write operation, and there is no performance penalty, though some specific instructions might require aligned operand (like the CAS instruction on PPC).