From: Rich Felker Date: Wed, 20 Jun 2012 16:07:18 +0000 (-0400) Subject: make strerror_r behave nicer on failure X-Git-Tag: v0.9.2~14 X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=f313a1622448de578ab0b11a881f44a02c9082e6;p=musl make strerror_r behave nicer on failure if the buffer is too short, at least return a partial string. this is helpful if the caller is lazy and does not check for failure. care is taken to avoid writing anything if the buffer length is zero, and to always null-terminate when the buffer length is non-zero. --- diff --git a/src/string/strerror_r.c b/src/string/strerror_r.c index 6fdd4ce2..907dcf07 100644 --- a/src/string/strerror_r.c +++ b/src/string/strerror_r.c @@ -4,8 +4,14 @@ int strerror_r(int err, char *buf, size_t buflen) { char *msg = strerror(err); - if (strlen(msg) >= buflen) + size_t l = strlen(msg); + if (l >= buflen) { + if (buflen) { + memcpy(buf, msg, buflen-1); + buf[buflen-1] = 0; + } return ERANGE; - strcpy(buf, msg); + } + memcpy(buf, msg, l+1); return 0; }