Defect report from : Glen Seeds , Cognos
(Please direct followup comments direct to yyyyyyyyyyyyyy@xxxxxxxxxxxxx)
@ page 1441 line 44878 section strerror objection {1}
Problem:
Edition of Specification (Year): 2004
Defect code : 2. Omission
strerror is not thread safe. strerror_r was introduced for this purpose.
Unfortunately, strerror_r has a serious usability problem. It requires the
caller to supply a fixed buffer for the result, but there is no way to
determine how big this buffer needs to be. The only way to make this work in
general is to supply an initial buffer, check for overflow, re-allocate, and
try again. Repeat until success, or you've used all available memory. Minimal
code looks something like this:
size_t buflen;
char *buf;
buflen = 100;
while (0 == (buf = malloc(buflen)) ) {
if (0 == (strerror_r(errno, buf, buflen)) ) break;
free(buf);
}
Note: In the proposed TR for secure C functions, strerror_s() does *not* solve
the usability problems identified above.
The simplest solution is to add a funciton to get the required
buffer size. The resulting code would be:
size_t buflen;
char *buf;
buflen = 1+strerrorlen(errno);
buf = malloc(buflen);
strerror_r(errno, buf, buflen);
Strerrorlen() is easy to implement efficiently, and does not impair the
readabaility of the application. While the malloc() approach used above does
have a performance impact, applications are not forced to do that. If simple
truncation is acceptable for the application, then the existing strerror_r() is
sufficient.
Action:
[at 44878 insert:]
int strerrorlen(int errnum)
[at 44899 insert:]
The strerrorlen function shall return the length of the string that would be
returned by strerror for the same errnum. This function shall be re-entrant.
|