tags:

views:

133

answers:

3

At some places in my code, I print debug messages like this:

int ret = getLinkSpeed(device.getSysName(), linkSpeed);
if (ret < 0)
{
    logDebug("Failed to obtain port speed for this device. Error: " + std::string(strerror(errno)));
}

From the documentation it is not entirely clear if strerror will return 0 under certain conditions (which would cause my code to crash). Does anyone know if it's safe?

+9  A: 

Why not write a function to do this:

string ErrStr() {
   char * e = strerror(errno);
   return e ? e : "";
}

This is easy to use, self-documenting, can be adapted to reformat the output and covers the possibility that strerror() might return NULL (I don't know if it can).

anon
I'd do return e?e:"unknown error"; at least messages that included such error description wouldn't look incomplete.
Matteo Italia
+3  A: 

Good question (+1), the documentation seems quite vague. I'm not sure if there is a "harder" source, such as the POSIX specification for instance.

Thinking a bit pragmatically, here is GNU libc's implementation. It returns a pointer to a static string buffer, so it cannot return 0.

In response to p00ya's comment, the safe (and also very pragmatical, heh) thing to do in the face of conflicting, vague or incomplete specifications is of course to assume the worst, and not assume that the return value will always be a valid string.

unwind
According to POSIX, in the cases where strerror itself has an error, the return value is undefined (although errno will be set). Going by specifications only I don't think you can rely on an accessible buffer being returned (whether or not it's 0).
p00ya
`strerror()` is defined in the C standard itself, where it is not allowed to fail.
caf
+2  A: 

Where you might get problems, is if you use a multi-threaded application. In this case, you need to use strerror_r

Nikko