Topics / Embedded C / Q37
Which compiler optimisations can change how your C code behaves?
An optimiser may transform code in any way that keeps the observable behaviour defined by the C standard. Code that relies on undefined behaviour, or that forgets to tell the compiler about hardware, can change behaviour between -O0 and -O2. The common ones:
- Caching values in registers / removing loads: a polled flag or register read once and never again. Fix with
volatile. - Dead-store elimination: writes the compiler thinks nobody reads are removed, such as clearing a key buffer before
freeor writing a register twice. Fix withvolatileorexplicit_bzero/memset_s. - Reordering: independent loads and stores may be moved, including across a write to a "data ready" flag. Fix with barriers or atomics.
- Assuming no undefined behaviour: signed overflow cannot happen (so
x + 1 > xbecomestrue), a dereferenced pointer cannot be NULL (so a later NULL check is deleted), shifts are smaller than the type width. - Strict aliasing: the compiler assumes an
int *and afloat *never point to the same memory, so type-punning through pointer casts can read stale values. - Loop transformations: empty delay loops are removed entirely; loops become
memcpy/memsetcalls (a problem inside your ownmemcpyor before.datais initialised). - Inlining and constant folding: can change timing and stack usage, and hide functions from the debugger.
The interview point is that the optimiser is not buggy; the code relied on something the language does not promise. Use volatile for hardware, atomics and barriers for concurrency, memcpy for type punning, and compiler warnings and sanitizers (-Wall -Wextra, UBSan) to find undefined behaviour.