It's different viewpoints...
Posted May 24, 2011 8:05 UTC (Tue) by farnz
In reply to: It's different viewpoints...
Parent article: What Every C Programmer Should Know About Undefined Behavior #3/3
But why do developers not realise that this is a problem? They're aware that triggering real machine undefined behaviour is a bad idea (e.g. poking random memory through a pointer set by casting the result of rand()).
I think the model of C as a "high level assembler" is part of what triggers this misunderstanding in developers; if you think that the C compiler does some trivial optimisations (constant folding and the like), then spits out a program that works on the real hardware in roughly the same way that it would work if you'd hand-assembled the C code yourself, you don't stop and think "hang on a minute, this might be undefined behaviour - the compiler could do anything".
Add to that the generally high quality of implementation of real compilers, such that undefined behaviour rarely bites you in the backside, and it can take a developer a long time to discover that their mental model of a C compiler as a thing that takes their input C code, and spits out machine code that does exactly what they would have done if they'd written the code in assembler for a machine they understand.
to post comments)