Tuesday, January 17, 2012

Undefined Behavior in C

Scenario 1

An aspect of the C standard (not unique to C) is that the behavior of certain code is said to be "undefined". In practice, this means that the program produced from this code can do anything, from working as the programmer intended, to crashing every time it is run.
For example, the following code produces undefined behavior, because the variable b is modified more than once with no intervening sequence point:
#include <stdio.h>
 
int main(void)
{
    int  a, b = 1;
 
    a = b++ + b++;
    printf("%d\n", a);
    return 0;
}
Because there is no sequence point between the modifications of b in "b++ + b++", it is possible to perform the evaluation steps in more than one order, resulting in an ambiguous statement. This can be fixed by rewriting the code to insert a sequence point in order to enforce an unambiguous behavior, for example:
a = b++;
a += b++;
or
a = (b += 2);

Useful Links:

Scenario 2
int main()
{
 int c=5;
 printf("%d\n%d\n%d", c, c <<= 2, c >>= 2);
 getchar();
}
Output: Compiler dependent
Evaluation order of parameters is not defined by C standard and is dependent on compiler implementation. It is never safe to depend on the order of parameter evaluation. For example, a function call like above may very well behave differently from one compiler to another.

No comments:

Post a Comment