Question

I am using strerror_r function from libc in Linux. I call it with 0 for the buffer pointer and buffer size arguments and it returns a pointer to a string with the error message.

I make a copy of the string for future use, but what to do with the returned pointer? Should I free this pointer in some way, or it points to some static message table?

Was it helpful?

Solution

The string returned by (the GNU, non-Posix) version of strerror_r is always either a static string, or the buffer you provide. It will almost always be a static string; error strings are dynamically created only when the value of errno is not known.

If you specify 0 for the buffer size, then your buffer will never be used. It will still be returned if it would have been necessary, which means that in your case, you might conceivably receive a 0 as the result of calling strerror_r. That's probably not what you intended.

The Posix version of strerror_r always uses the buffer you supply, and return 0 unless some error occurred (running out of buffer would be an error, so if you specify buffer as 0 with the Posix version, you're guaranteed to get an error return, which will -- as a side-effect -- destroy the previous value of errno.

In short:

  1. Calling strerror_r with a buffer length of 0 is not correct, although if you use the Gnu-specific version of that function, the vast majority of the time it won't matter.

  2. You don't need to copy the string unless it is your buffer. With the Posix-compatible version of strerror_r, it's impossible to know whether a static string might have been available, so you will always end up copying the buffer.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top