- 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() { return ++count; }
  4. int g() { return ++count >= 2 ? 5 : 3; }
  5. int h(int a, int b) { return a+b; }
  6. int main() {
  7. int x = h(f(), g());
  8. printf ("%d\n", x);
  9. int y = 3;
  10. y = (y += 1) + (y = y*y);
  11. printf ("%d\n", y);
  12. }
  1. $ clang -Wall undefined.c
  2. undefined.c:13:21: warning: unsequenced modification and access to 'y' [-Wunsequenced]
  3. y = (y += 1) + (y = y*y);
  4. ~~ ^
  5. 1 warning generated.
  6. $ ./a.out
  7. 6
  8. 20
  • a=f(), b=g(), a+b
  • y=y+1; y=y+y*y

Undefined Order of Operations

  1. #include <stdio.h>
  2. int count = 0;
  3. int f() { return ++count; }
  4. int g() { return ++count >= 2 ? 5 : 3; }
  5. int h(int a, int b) { return a+b; }
  6. int main() {
  7. int x = h(f(), g());
  8. printf ("%d\n", x);
  9. int y = 3;
  10. y = (y += 1) + (y = y*y);
  11. printf ("%d\n", y);
  12. }
  1. $ gcc -Wall -O3 undefined.c
  2. undefined.c:13:21: warning: unsequenced modification and access to 'y' [-Wunsequenced]
  3. y = (y += 1) + (y = y*y);
  4. ^
  5. $ ./a.out
  6. 5
  7. 32
  • b=g(), a=f(), a+b
  • y=y+1; y=y*y; y=y+y;

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