vp_arth
vp_arth

Reputation: 14982

GNU strerror_r buffer meaning

char *strerror_r(int errnum, char *buf, size_t buflen);

What are these buf/buflen parameters for?

Empty buffer works like a charm:

char* buf = nullptr;
fprintf(stderr, strerror_r(errno, buf, 0));

Also this buffer looks like unused:

char buf[1024];
fprintf(stderr, "%s\n", strerror_r(errno, buf, sizeof buf)); // Correct message here
fprintf(stderr, "%s\n", buf); // Empty

Upvotes: 2

Views: 1284

Answers (2)

mymedia
mymedia

Reputation: 617

As you noticed in comments, buf and buflen parameters is used only if you pass invalid errnum, negative or unknown errno value. This is confirmed by the source code of the function.

char *
__strerror_r (int errnum, char *buf, size_t buflen)
{
  if (__builtin_expect (errnum < 0 || errnum >= _sys_nerr_internal
                        || _sys_errlist_internal[errnum] == NULL, 0))
    {
      /* To fill up buf with "Unknown error" localized string and to append
         digits of errnum. Nothing happens if buflen equals zero. */

      ...

      return buf;
    }

  return (char *) _(_sys_errlist_internal[errnum]);
}

In relation capacity of the buffer, I think 1024 bytes will be enough. Moreover, it's the exact same size which strerror implementation uses (that's thread unsafe). See also the related answer and the comment to it.

Of course, it all is concern of GNU-version of the function. XSI-compliant version always uses this buffer for copy of a static string.

Upvotes: 2

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

Quoting from the man page, emphasis mine

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).

So it is very much possible that buf is left unused and in case, buf is unused, the buflen does not matter.

[....] 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). [...]

Upvotes: 3

Related Questions