Undefined Behavior - Examples in C and C++

Examples in C and C++

Attempting to modify a string literal causes undefined behavior:

char * p = "wikipedia"; // ill-formed C++11, deprecated C++98/C++03 p = 'W'; // undefined behaviour

One way to prevent this is defining it as an array instead of a pointer.

char p = "wikipedia"; /* RIGHT */ p = 'W';

In C++ one can use STL string as follows.

std::string s = "wikipedia"; /* RIGHT */ s = 'W';

Division by zero results in undefined behavior; under IEEE 754, the division of float, double, and long double values by zero results in an infinity or NaN:

return x/0; // undefined behavior

Certain pointer operations may result in undefined behavior:

int arr = {0, 1, 2, 3}; int* p = arr + 5; // undefined behavior

Reaching the end of a value-returning function (other than main) without a return statement may result in undefined behavior:

int f { } /* undefined behavior */

The C Programming Language cites the following examples of code that have undefined behavior in Section 2.12:

printf("%d %d\n", ++n, power(2, n)); /* WRONG */

and

a = i++;

Read more about this topic:  Undefined Behavior

Famous quotes containing the word examples:

    There are many examples of women that have excelled in learning, and even in war, but this is no reason we should bring ‘em all up to Latin and Greek or else military discipline, instead of needle-work and housewifry.
    Bernard Mandeville (1670–1733)