C++ Logo


Advanced search

Re: [ub] Type punning to avoid copying

From: Ion Gazta˝aga <igaztanaga_at_[hidden]>
Date: Fri, 26 Jul 2013 01:03:32 +0200
El 25/07/2013 18:10, Kazutoshi Satoda escribiˇ:
> 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)

A very useful example. I don't think many C/C++ programmers would
correctly answer the question. I couldn't. And we have tons of code and
years of existing practice using this union hack.

┐How can we tell the compiler that a memory buffer is really a different
type? This is a typical situation when handling network packets, mapping
files or shared memory, when passing data though message queues.
Situations where we expect C/C++ will be extremely efficient.

We can tell the compiler to avoid some optimizations via "volatile" or
"atomic<>". Maybe another mechanism is needed to tell the compiler
(provided the memory region is correctly aligned for the type) that it
should reinterpret the memory region as the a new type (without calling
placement new on the buffer, which could overwrite the bits written in
the buffer).



Received on 2013-07-26 01:03:53