[ub] Type punning to avoid copying (was: unions and undefined behavior)

Kazutoshi Satoda k_satoda at f2.dion.ne.jp
Thu Jul 25 18:10:38 CEST 2013


On 2013/07/25 09:05 +0900, Nevin Liber wrote:
> struct UDPHeader : IPHeader
> {
>     //...
>     uint16_t length;
>     //...
>     char     data[1];
> };
...
>             f(&header.udp.data[0], &header.udp.data[header.udp.length - 8]);
...
> Q1:  How many places has undefined behavior been invoked in the above?

Aside from the one that Jeffrey pointed out (accessing char array via
an glvalue of type Header), I found one at the second array subscription
above. If header.udp.length is greater than 9, the index goes beyond
the end of the array (char data[1]), and triggers undefined behavior.
5.7 [expr.add] p5
> ... If both the pointer operand and the result point to elements of the
> same array object, or one past the last element of the array object, the
> evaluation shall not produce an overflow; otherwise, the behavior is
> undefined.

I know this is not related to the original topic (type punning), though.
-- 
k_satoda


More information about the ub mailing list