Pages: 1
  Print  
Author Topic: Undefined behavior  (Read 2634 times)
Offline (Unknown gender) luiscubal
Posted on: November 08, 2011, 02:15:37 pm
Member
Joined: Jun 2009
Posts: 452

View Profile Email
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.
Logged
Pages: 1
  Print