Hacker News·7 min read·hard

Type Punning in C and C++

I
ingve
AI Summary

This technical article explains the risks and mechanics of type punning in C and C++ programming. It details why pointer casting is considered undefined behavior and suggests safer alternatives like unions and memcpy.

Why it matters

Understanding memory management and strict aliasing rules is critical for developers writing high-performance, low-level code to avoid silent bugs.

Dive DeeperCreate a free account to unlock

c undefined-behavior c++ About 7 min read I had a bug that took me a while to track down. The problem was type punning. A pointer cast worked fine at -O0 and silently broke at -O2 . The C vs C++ distinction here is genuinely treacherous, and most blog posts on the topic get it wrong.

Type punning is interpreting memory as different types between reads and writes. It’s essential for serialisation, network protocols, and low-level hardware access.

The problem is that “works in practice” and “has defined behaviour” are different things.

In C, the safe ways to type pun are union and memcpy . Pointer casts are technically undefined behavior under strict aliasing rules, even though they work on every compiler you’ll encounter.

A union lets you write as one type and read as another. This is defined behavior in C:

Continue reading on Headlinne

Create a free account to read the full article.

Read full article →
technologyscience

Get smarter about the news

Sign up free for a feed built around what you actually care about, Dive Deeper research on any story, and the full text of every article.

Create free account

Already have an account? Sign in