I have the following struct:
struct foo
{
int a;
char b;
};
It is stored to memory and pointer to it can be unaligned (odd address).
So, is this safe?:
const struct foo a = *((struct foo*)char_ptr);
I am worrying, because the integer member of the source struct can be in odd address. In some systems reading of (multi byte) integer from odd adderess causes problems.
EDIT:
For avoiding off-topic commenting about usage of const, I did remove a const from the code. (I never cast const pointer to non-const pointer, even in this case where it should not cause any problems)
And more about context of problem:
This kind of structure is part of protocol frame. And it can be in any offset inside the frame. In the real code the struct have __attribute__((packed)) attribute. But that probably not change the answer?
Anyway, I could use memcopy and non-const a for solving the problem. But I would like to use the assingment, because it seems to be more elegant way (if it is safe).
No, it is not safe, unless you know the pointer has the alignment required for the structure.
Here are some ways to know the pointer has the necessary alignment:
malloc) that guarantees the address returned is suitably allocated for any use (whichmallocdoes guarantee).uintptr_tand test its alignment, provided this is supported by your C implementation.If you do not know the pointer has the necessary alignment, then you should not access the structure through a converted pointer. Instead, you can define a new structure and use
memcpyto copy from the pointer-to-char into the new structure.