2015年11月13日 星期五

Undefined, unspecified and implementation-defined behavior


Undefined behavior
The effect of attempting to modify a string literal is undefined.
 accessing an array beyond its bounds, dereferencing the null pointer
writing allegedly clever expressions like i++ + ++i.

Use of an uninitialized variable
Signed integer overflow:
Oversized Shift Amounts
Dereferences of Wild Pointers and Out of Bounds Array Accesses:
Dereferencing a NULL Pointer
Violating Type Rules: It is undefined behavior to cast an int* to a float* and dereference it
   ==> dereferencing a pointer that aliases another of an incompatible type is undefined behavior.

WHAT IS STRICT ALIASING?
Strict aliasing is an assumption, made by the C (or C++) compiler, that dereferencing pointers to objects of different types will never refer to the same memory location (i.e. alias eachother.) 


implementation-defined behavior
Certain aspects and operations of the abstract machine are described in this International Standard as implementation-defined (for example, sizeof(int)). These constitute the parameters of the abstract machine. Each implementation shall include documentation describing its characteristics and behavior in these respects.

The language says that we have data-types. The compiler vendors specify what sizes shall they use, and provide a documentation of what they did.

unspecified behavior

Certain other aspects and operations of the abstract machine are described in this International Standard as unspecified (for example, order of evaluation of arguments to a function). Where possible, this International Standard defines a set of allowable behaviors. These define the nondeterministic aspects of the abstract machine.
The language doesn't specify the evaluation,







how to avoid

For example, using the -fwrapv flag eliminates undefined behavior that results from signed integer overflow 
If writing code in a non-portable dialect of C isn't your thing, then the -ftrapv and -fcatch-undefined-behavior flags (along with the other tools mentioned before) can be useful weapons in your arsenal to track down these sorts of bugs

 -fcatch-undefined-behavior is deprecated

-ftrapv This option generates traps for signed overflow on addition, subtraction, multiplication operations. 
-fwrapv This option instructs the compiler to assume that signed arithmetic overflow of addition, subtraction and multiplication wraps around using twos-complement representation. This flag enables some optimizations and disables others. This option is enabled by default for the Java front-end, as required by the Java language specification. 

沒有留言:

張貼留言