Reputation: 6200
Is this code safe:
strerror_r(errcode,buffer,length);
printf("Error: %s",buffer);
That is, can I trust buffer to be null terminated in case the buffer is to small? From the man page:
The XSI-compliant strerror_r() is preferred for portable applications. It returns the error string in the user-supplied buffer buf of length buflen.
The GNU-specific strerror_r() returns a pointer to a string containing the error message. This may be either a pointer to a string that the function stores in buf, or a pointer to some (immutable) static string (in which case buf is unused). If the function stores a string in buf, then at most buflen bytes are stored (the string may be truncated if buflen is too small and errnum is unknown). The string always includes a terminating null byte ('\0').
Am I right that if I use the XSI-compliant version, it may happen that buffer is not null terminated.
Upvotes: 1
Views: 725
Reputation: 6200
Here is the changelog for xpg-strerror.c:
2011-05-21 Ulrich Drepper Always fill output buffer in XPG strerror function blob | commitdiff | diff to current
2010-12-25 Ulrich Drepper Change XPG-compliant strerror_r function to return... blob | commitdiff | diff to current
So if I assume a decent version of glibc, everything seems to be fine. Unless some guy reverts the change.
Upvotes: 0
Reputation: 1493
If you’re using the POSIX strerror_r
and it returns non-zero, I’m not sure that you can assume that anything at all is in buffer
. You can check man 3p strerror
for the POSIX function description, but it doesn’t say what happens to buffer
if length
isn’t large enough.
Maybe some other part of the POSIX standard says what happens in situations like this, but I suspect that it isn’t specified. I would check the return value of strerror_r
, and not use buffer
if it’s non-zero, just to be safe.
On two systems where I tried this, the compiler copied the error message into the buffer and truncated it with a NUL byte. On RHEL 5.4, strerror_r
did not modify buffer
if its size was too small. In that case, buffer
could be anything, if you didn't initialize it before caling sterror_r
.
Upvotes: 2