...
Consider a multithreaded application that encounters an error while calling a system function. The strerror()
function returns a human-readable error string given an error number. C99, Section 7.22.6.2, specifically states that strerror()
is not required to avoid data races. Conventionally, it could rely on a static array that maps error numbers to error strings, and that array might be accessible and modifiable by other threads.
Code Block | ||||
---|---|---|---|---|
| ||||
errno = 0; FILE* fd = fopen( filename, "r"); if (fd == NULL) { char* errmsg = strerror(errno); printf("Could not open file because of %s\n", errmsg); } |
...
The compliant solution uses the POSIX strerror_r()
function, which has the same functionality as strerror()
but guarantees thread safety.
Code Block | ||||
---|---|---|---|---|
| ||||
errno = 0; FILE* fd = fopen( filename, "r"); if (fd == NULL) { char errmsg[BUFSIZ]; if (strerror_r(errno, errmsg, BUFSIZ) != 0) { /* handle error */ } printf("Could not open file because of %s\n", errmsg); } |
...