Strerror_r returns garbage when I manually set errno during testing

During testing, I have a mock object that sets errno = ETIMEDOUT; The object I'm testing sees an error and calls strerror_r to return an error string:

 if (ret) { if (ret == EAI_SYSTEM) { char err[128]; strerror_r(errno, err, 128); err_string.assign(err); } else { err_string.assign(gai_strerror(ret)); } return ret; } 

I do not understand why strerror_r returns the cart. I even tried to call

 strerror_r(ETIMEDOUT, err, 128) 

straight and still have trash. I have to miss something. It seems I am getting a gnu version of a non posix function, but this should not make any difference in this case.

Edit

I'm on Ubuntu 8.04. The glibc version looks like 2.7 in feature.h.

+4
source share
2 answers

According to this page http://linux.die.net/man/3/strerror_r , if you are using the GNU strerror_r() version, the function may decide not to store anything at all in the buffer that you provide; you will need to use the line returned by the function (it looks like a rather strange interface):

The GNU-specific strerror_r() returns a pointer to a string containing an error message. This can be either a pointer to a string that the function stores in buf, or a pointer to some (immutable) static string (in this case, buf is not used). If the function stores the string in buf, no more than byte bytes are stored (the string can be truncated if buflen is too small), and the string always includes a terminating null byte.

So, if you are using the GNU version, you cannot rely on your err buffer to have something useful in it if strerror_r() does not return the err address.

+10
source

The problem is that Linux has two strerror_r functions. If you read the manual,

  int strerror_r(int errnum, char *buf, size_t buflen); /* XSI-compliant */ char *strerror_r(int errnum, char *buf, size_t buflen); /* GNU-specific */ The XSI-compliant version of strerror_r() is provided if: (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && ! _GNU_SOURCE 

The g ++ compiler automatically detects _GNU_SOURCE, so you are using the GNU version for a function that does not necessarily store the message in the buffer you specify.

+4
source

Source: https://habr.com/ru/post/1312934/


All Articles