Undefined Behavior
Definition
The term undefined, or undefined behavior, means that no
restrictions are placed on the behavior of a program in certain
circumstances. It is not the same as an error condition.
Example
int main() {
return 1/0;
}
c.c: In function 'main':
c.c:2: warning: division by zero
SIGFPE: Floating point exception
The C and C++ standards says that a program that divides by zero invokes
undefined behavior. This means that an implementation places no
restrictions on the behavior of such a program. That is, it may do
anything, including but not restricted to:
- detecting the error at runtime and producing an error message
- detecting the error at compile time, if possible
(our implementation does this)
- producing a Linux signal
(our implementation does this)
- returning a special infinite value
- returning the value 42
- returning the result of dividing by one, instead
- going into an infinite loop
- printing the message “
you are ugly
”
Those aren’t all good possibilities, but, since undefined behavior
puts no restrictions on possible actions, they are all allowed by
the C and C++ standards.
Why
Why allow undefined behavior? To not restrict implementations. The C
and C++ standards realize that requiring any particular behavior would,
for some computer architectures, result in unnecessarily slow or large
programs. Instead, the standards merely state that division by zero
invokes undefined behavior, so that each implementation can do whatever
is reasonable for those circumstances.
Another Example
A homework programming assigment might specify:
- If the input is two numbers, subtract them.
- If the input is three numbers, add them.
- More than three numbers results in undefined behavior.
The third line is another way of saying that we don’t care what
happens if there are more than three numbers. These would all be ok
responses, if four numbers are given:
- Produce an error message stating that no more than three numbers are
permitted.
- Print “
BAD!
” and stop the program.
- Print “
BAD!
” and don’t stop the program.
- Print “
I like cookies
” and go into an infinite loop.
- Ignore the input completely.
- Add the first three numbers.
- or, literally, anything else
Testing
What will a TA or a grader do in an undefined behavior situation?
They will ignore it. They won’t test it; since any behavior
is acceptable, why bother writing a test that can never fail?