In the code below could somebody perhaps explain what is happening on the line struct ether_header *eh = (struct ether_header *) sendbuf;
? I understand that it
But how can you do this
isifsendbuf
is achar
array?
Code should not do this.
Casting a pointer to a type that was not originally a valid pointer for that type is undefined behavior (UB).
char sendbuf[BUF_SIZ];
struct ether_header *eh = (struct ether_header *) sendbuf; // UB
At a minimum, consider if struct ether_header
had an alignment requirement to be an even address and sendbuf[]
began on an odd address. The assignment may kill the program.
A 2nd concern is what unposted code might later do with sendbuf[]
and eh
which can violating strict aliasing rule @Andrew Henle.
A better approach is to use a union
. Now the members are aligned and the union
handles the strict aliasing rule.
union {
char sendbuf[BUF_SIZ];
struct ether_header eh;
} u;
Also why would you do this?
To allow access to the data from 2 data type perspectives. Perhaps to make a data dump of u
.