As far as I understand, the following piece of code exhibits undefined behaviour in C11:
#include <string.h>
struct aaaa { char bbbb; int cccc; };
int main(void) {
unsigned char buffer[sizeof(struct aaaa)] = { 0 };
struct aaaa *pointer = &buffer[0];
return (*pointer).cccc;
}
According to N1570 section 6.5.3.2 clause 4,
If an invalid value has been assigned to the pointer, the behavior of the unary
*
operator is undefined.
which is accompanied by a footnote that clarifies that
Among the invalid values for dereferencing a pointer by the unary
*
operator are a null pointer, an address inappropriately aligned for the type of object pointed to, and the address of an object after the end of its lifetime.
It's unlikely that struct aaaa *
and unsigned char *
have the same alignment, so we assigned an invalid value to pointer
, and using *pointer
therefore causes UB.
However, can I copy the structure?
#include <string.h>
struct aaaa { char bbbb; int cccc; };
int main(void) {
unsigned char buffer[sizeof(struct aaaa)] = { 0 };
struct aaaa target;
memcpy(&target, buffer, sizeof(struct aaaa));
return target.cccc;
}
Here, we pass a struct aaaa *
and unsigned char *
to memcpy
. While that seems just as bad as the first piece of code, I can't find any wording in C11 that rules that this code exhibits UB. Does this usage of memcpy
cause undefined behaviour?