- Concepts of Programming Languages

Undefined Behavior

Instructor:

Learning Objectives

What should happen if the language does not specify the meaning of some construct?
What should happen when x is holding 8 bits, x=7 and then x = x+1?

  • Identify undefined behavior in C

Datatype Bounds

  • Natural numbers are only partly useful as integer arithmetic semantics
  • Add integer bounds
  • What to do with overflow?
    • Error:

Under and Overflow

  1. #include <stdio.h>
  2. int isMinValue (int x) {
  3. return (x-1) > x;
  4. }
  5. int main () {
  6. int i = -2000000000;
  7. while (!isMinValue(i))
  8. i--;
  9. printf ("Min value is %d\n", i);
  10. }
  1. $ gcc -O1 undefined.c && ./a.out
  2. Min value is -2147483648
  1. $ gcc -O2 undefined.c && ./a.out
  2. ^C #infinite loop

Order of Operations

  • Recall rule for sequential composition
  • Rule define an order of evaluating subexpressions
    • by chaining the stores
    • is used in evaluating and produces
    • is used in evaluating and produces

Undefined Order of Operations

  1. #include <stdio.h>
  2. int count = 0;
  3. int f () {
  4. count += 1;
  5. return count;
  6. }
  7. int main () {
  8. int z = f() + f();
  9. printf ("%d\n", z);
  10. z = (z += 1) + (z = z*z);
  11. printf ("%d\n", z);
  12. }
  1. $ clang -Wall undefined3.c
  2. undefined3.c:11:21: warning: unsequenced modification and access to 'z'
  3. z = (z += 1) + (z = z*z);
  4. ~~ ^
  5. 1 warning generated.
  6. $ ./a.out
  7. 3
  8. 20
  • z=z+1; z=z+z*z

Undefined Order of Operations

  1. #include <stdio.h>
  2. int count = 0;
  3. int f () {
  4. count += 1;
  5. return count;
  6. }
  7. int main () {
  8. int z = f() + f();
  9. printf ("%d\n", z);
  10. z = (z += 1) + (z = z*z);
  11. printf ("%d\n", z);
  12. }
  1. $ gcc -Wall -O3 undefined3.c
  2. undefined3.c: In function ‘main’:
  3. undefined3.c:11:5: warning: operation on ‘z’ may be undefined
  4. z = (z += 1) + (z = z*z);
  5. ^
  6. $ ./a.out
  7. 3
  8. 32
  • z=z+1; z=z*z; z=z+z;

Compiler Optimizations

  • For undefined executions, the compiler can do what it likes
  • This can lead to some surprising compiler optimizations
  • C null pointer optimization 1

Summary