Sunday, February 20, 2011

Undefined Behavior.....

Kernighan and Ritchie wisely point out, ``if you don't know how they are done on various machines, that innocence may help to protect you.''

The C specifications are interesting because they leave many behaviors undefined. For example, if you try to use an uninitialized variable, the results are technically undefined.n some languages, the specifications might stipulate that if that ever happened, the program should gracefully halt with an error message or something. Or that all variables be initialized with default values as soon as they’re declared. The architects of C decided to leave it up to the compiler-makers to decide how to handle it. The reason is optimization. If the language’s designers required a graceful halt upon use of an uninitialized variable, then in order to be compliant, compiler-makers would have to build that into their compilers… which comes with a performance cost...

 Some other behaviors which create undefined result:
  • Division by Zero. In practice, this usually results in the program halting (possibly with a core dump), but it doesn’t have to, according to the C standards. 1/0 could be defined to be absolutely anything, and computing it might cause the computer to format its hard-drive– that would still be C-compliant.
  • i++ += i + i++. Assume i starts at 0… what do you think i should become after this operation? The more general rule is: any time you try to read a variable twice within a computation in which you also write to that variable, the behavior is undefined.
  • Trying to read or write from memory which hasn’t been allocated. Thus all the trouble with buffer overflows.

void main()
int i=10;
void f(int a,int b,int c)

Explanation:The behavior of this program is undefined in the C standard..this depend on the compiler implementation and vary from compiler to compiler..The behavior is due to function call f(i++,i++,i++) due to the sequence points concept....


Feel free to comment......