...
This noncompliant code example uses the complement operator in the test for unsigned integer overflow.
Code Block | ||||
---|---|---|---|---|
| ||||
unsigned int ui1, ui2, sum; if (~ui1 < ui2) { /* handle error condition */ } sum = ui1 + ui2; |
...
This compliant solution implements a strictly conforming test for unsigned overflow.
Code Block | ||||
---|---|---|---|---|
| ||||
unsigned int ui1, ui2, sum; if (UINT_MAX - ui1 < ui2) { /* handle error condition */ } sum = ui1 + ui2; |
...
The GNU libc implementation of strerror_r declares the function to return char*
, in conflict with the POSIX ® specification. The following noncompliant code example relies on this return type to pass the return value as an argument to the %s
formatting directive to fprintf
. The behavior of the example will be undefined on a platform that declares the return type of strerror_r()
to be int
, in accordance with POSIX.
Code Block | ||||
---|---|---|---|---|
| ||||
void f() { char buf[80]; fprintf(stderr, "Error: %s\n", strerror_r(errno, buf, sizeof buf)); } |
...
Note that the function assigns the result of the call to strerror_r()
to a variable of type int
. This assignment is a defense-in-depth strategy guarding against inadvertently invoking strerror_r()
that returns char*
: a conforming compiler is required to issue a diagnostic for the ill-formed conversion from char*
to int
.
Code Block | ||||
---|---|---|---|---|
| ||||
#define _XOPEN_SOURCE 600 #include <string.h> void f() { char buf[80]; int result; result = strerror_r(errno, buf, sizeof buf); if (0 != result) strcpy(buf, "Unknown error"); fprintf(stderr, "Error: %s\n", buf); } |
...