...
The compliant solution below disables the non-conforming declaration of strerror_r
by explicitly requesting POSIX conformance before including the <string.h>
header that declares the function and handles the function's failure by copying the "Unknown error"
string into the buffer.
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]; if (0 != strerror_r(errno, buf, sizeof buf)) strcpy(buf, "Unknown error")int result; fprintf(stderr, "Error: %s\n", buf); } |
The following alternate compliant solution avoids relying on the return type of strerror_r
and takes care to set the first character of the buffer to NUL
before calling the function to detect its success or failure and copies the "Unknown error"
string into the buffer on failure.
Code Block | ||
---|---|---|
| ||
void f() { char buf[80]; buf[0] = '\0'; result = strerror_r(errno, buf, sizeof buf); if ('\0' =!= buf[0]result) strcpy(buf, "Unknown error"); fprintf(stderr, "Error: %s\n", buf); } |
...