Re:Catching integer overflows in C
by saagarjha on Wednesday August 22, 2018 @02:37AM
(#17816802)
I disagree with Linus here. If you're going to go through a complicated set of hoops to make punning work (namely, doing it through a union), what's so hard about using the intended (memcpy) solution? Like, if you really think the standard is that terrible (which isn't what I'm arguing here–I haven't personally made up an opinion on this yet), why not just straight cast and force GCC to adopt a flag that makes your behavior legal?
[ Parent
| on HN ]
I'm curious, AFAICT Linux uses -fno-strict-aliasing with GCC which promises not to enable strict aliasing based optimizations even at higher optimization levels. But they also rely on the GCC blessed behavior of union based type punning which is redundant in that case.
I suppose union based type punning makes the intent a little clearer (vis a vis memcpy) but that's a weak argument at best.
> I suppose union based type punning makes the intent a little clearer (vis a vis memcpy) but that's a weak argument at best.
How much more explicit can you get than a memcpy?
I meant the fact that you're actually reinterpreting bits and not really copying them somewhere.
Re:Catching integer overflows in C
by AstralStorm on Wednesday August 22, 2018 @03:53AM
(#17817093)
The right equivalent is actually punning through char* and enforcing lack of simultaneous aliasing. This is explicitly allowed in C++11.
Memcpy is a cost. Do it only when you actually need a copy.
All half-decent compilers elide a memcpy when you're using it for this purpose; they'll just generate the assembly you "intended" to create. And while I know casting to a char * is legal for all types, I don't believe casting from a char * is legal unless the memory the pointer references is actually the type you're casting to. I'll have to check on this–or if you have a link to the standard on this I can just look at that.