Recently, I got to learn about Strict Aliasing in C. It is yet another thing that can cause your C code work perfectly fine today and then blow up because of Undefined Behavior down the line. One example of what not to do is casting an array of (like a payload from a communications protocol) into a struct (like the message you are receiving):uint8_t
void receive_data(uint8_t * payload, uint16_t length) {
... // Sanity checking etc
my_struct_t * my_struct = (my_struct_t *) payload; // Don't do this!
do_stuff(my_struct->some_field);
}
A better way is to use :memcpy
void receive_data(uint8_t * payload, uint16_t length) {
... // Sanity checking etc
my_struct_t my_struct;
memcpy(my_struct, payload, sizeof(my_struct_t)); // Do this instead!
do_stuff(my_struct.some_field);
}
One reason this kind or “reinterpret cast” is not allowed is that you can’t be sure that accessing a field within the struct after typecasting will be a properly word-aligned memory access.
For more details, here is a write-up with more examples which also explains the situation for C++: https://gist.github.com/shafik/848ae25ee209f698763cffee272a58f8
Leave a Reply