1

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.

1
  • @yellowantphil RHEL 5.4 is not relevant, unless the kernel has been upgraded to version 2.6.36, and gcc to 4.8. Commented Jan 5, 2015 at 19:44

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.