News for hackers. Stuff that matters.
Re:totally_safe_transmute, Line-by-Line (2021) by kazinator on Monday January 08, 2024 @06:19PM (#38919868)
C doesn't provide any reinterpretation operator, and the C++ one's name is a misnomer.

Casts are conversion: a new value is produced based on an existing one.

Reinterpretation requires a value to be in memory, and to be accessed using an lvalue of a different type. Most situations of this kind are undefined behavior.

Re:totally_safe_transmute, Line-by-Line (2021) by Joker_vD on Monday January 08, 2024 @09:32PM (#38921529)

   double transmute_int_to_double(int x) {
       double result = 0;
       memcpy(&result, &x, sizeof(int) < sizeof(double) ? sizeof(int) : sizeof(double));
       return result;
   }
is not a UB, and it doesn't even necessarily touch any memory:

    transmute_int_to_double:
        movd    xmm0, edi
        ret
[0] https://godbolt.org/z/czM3eh8er
Re:totally_safe_transmute, Line-by-Line (2021) by kazinator on Monday January 08, 2024 @11:53PM (#38922480)
> is not UB

Not by my interpretation of n3096 (April 2023 ISO C draft).

> doesn't even necessarily touch any memory

The abstract semantics calls for memory being touched. Data flows that go through memory in the abstract semantics can be optimized not to go through memory. UB can do anything at all.

Re:totally_safe_transmute, Line-by-Line (2021) by aw1621107 on Tuesday January 09, 2024 @03:32AM (#38923722)
> Not by my interpretation of n3096 (April 2023 ISO C draft).

What clause(s) support the claim that that example is UB? At least at first glance it looks pretty similar to the sometimes-recommended way to perform safe type-punning in C, and the only way to "directly" invoke UB via memcpy (passing pointers to overlapping objects) isn't relevant here.

The only suspicious part to me is the size/number of bytes to copy, but I'm not sure that's outright UB?

Re:totally_safe_transmute, Line-by-Line (2021) by kazinator on Tuesday January 09, 2024 @04:09AM (#38923917)
We have no idea whether the bytes that were copied into that object are a valid representation.
Re:totally_safe_transmute, Line-by-Line (2021) by aw1621107 on Wednesday January 10, 2024 @10:58AM (#38939978)
Ah, I didn't think of that.

That being said, is there a representation for doubles that could be considered invalid? I thought all double bit patterns are interpretable as a "valid" double, even if you get NaNs.

Re:totally_safe_transmute, Line-by-Line (2021) by lifthrasiir on Tuesday January 09, 2024 @01:28AM (#38923073)
You can alternatively read `reinterpret_cast` as "casting or convesion used to achieve reinterpretation", which is clearly correct.