C Programming · Interview question

What is the strict aliasing rule and how do you safely reinterpret bytes?

A strong answer

Strict aliasing is the rule that lets the compiler assume two pointers of incompatible types never point at the same object (with a special exception for char *, which may alias anything). This assumption enables it to cache a value in a register across a write made through a different-typed pointer. If you violate it, e.g. write a float then read its bits through an int * cast, you get undefined behavior, and the optimizer may use a stale cached value or reorder accesses, miscompiling silently. The safe, portable way to reinterpret an object's bytes is memcpy(&dst, &src, sizeof dst): it's defined regardless of types, and compilers recognize the idiom and lower it to a plain move with no actual copy. In C (but not C++), reading a different member of a union than the one written is also permitted for type-punning. This matters in embedded when reinterpreting register values, serializing structs to byte buffers, or deserializing wire data.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

Undefined Behavior & Pitfalls

Why code that works at -O0 breaks at -O2: what undefined behavior is, the catalog of UB every firmware engineer must recognize, and how sanitizers catch it.

More Undefined Behavior & Pitfalls questions

Browse all 472 interview questions
What is the strict aliasing rule and how do you safely reinterpret bytes? | EmbeddedPrep.io