hn.today

Type Punning in C and C++

blog.pwkf.org35 points23 comments
Screenshot of Type Punning in C and C++

This explains what type punning is - reading memory with a different type than it was written - and why it matters for serialization, network formats, and hardware access. It lays out safe, defined ways to pun in C: using a union to write one member and read another (example: float/uint32_t to extract IEEE-754 bits) or using memcpy, which the compiler will typically optimize to a register move. It warns that casting pointers to unrelated types is technically undefined behavior under the strict aliasing rule, even though such casts often “work” on real compilers until optimization makes them fail.

It contrasts C and C++ behavior: C treats types as interpretations of memory, while C++ treats types as stronger guarantees that the compiler can assume never alias, enabling more aggressive optimizations. A concrete example shows passing a uint64_t and a struct that overlap in memory; with GCC/Clang at -O2 the code returns 2 but at -O1 it returns 0 because the optimizer removed a read based on non-aliasing assumptions. The practical rule is clear: use unions or memcpy for reliable punning; pointer casts are convenient but can silently break at higher optimization levels. A pointer-cast bug in a hot loop was fixed by switching to a union.

Read on blog.pwkf.org23 comments on Hacker News

Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.

More in Security

The daily digest

Today's best Hacker News stories, summarized and screenshotted, one email a day.