ENIGMA Forums

Sharing is caring => Tips, Tutorials, Examples => Topic started by: luiscubal on November 08, 2011, 02:15:37 pm

Title: Undefined behavior
Post by: luiscubal on November 08, 2011, 02:15:37 pm
Some guys from LLVM/Clang have published a bunch of posts explaining what undefined behavior in C is and what are its implications.

http://blog.llvm.org/2011/05/what-every-c-programmer-should-know.html
http://blog.llvm.org/2011/05/what-every-c-programmer-should-know_14.html
http://blog.llvm.org/2011/05/what-every-c-programmer-should-know_21.html

This gets tricky because they add info about optimizers, so undefined behavior really doesn't always behave like one would expect.
For instance, one of the examples they give is this:

Code: [Select]
void contains_null_check(int *P) {
  int dead = *P;
  if (P == 0)
    return;
  *P = 4;
}{/code]
In the above example, one could expect that "dead" would be removed by the optimizer, so the code would be safe.
However, depending on how the optimizer is made, this may not be the case. This is a perfectly valid optimizer result:
[code]void contains_null_check_after_RNCE(int *P) {
  int dead = *P;
  if (false)  // P was dereferenced by this point, so it can't be null
    return;
  *P = 4;
}
Code: [Select]
void contains_null_check_after_RNCE_and_DCE(int *P) {
//removed dead variable since it's never used.
//if(false) removed
*P = 4;
}

The whole thing is very interesting and, in my opinion, a must-read for all C/C++ programmers.