C++ Logo


Advanced search

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

From: Kazutoshi Satoda <k_satoda_at_[hidden]>
Date: Fri, 26 Jul 2013 01:10:38 +0900
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.

Received on 2013-07-25 18:16:48