make semantics of custom strndup() comply with glibc
authorPhil Sutter <phil@nwl.cc>
Mon, 8 Dec 2008 23:12:23 +0000 (00:12 +0100)
committerPhil Sutter <phil@nwl.cc>
Thu, 11 Dec 2008 14:28:21 +0000 (15:28 +0100)
From strdup(3):
| If s is longer than n, only n characters are copied, and a
| terminating null byte ('\0') is added.

So allocate at most n+1 bytes and make sure the last one is zero, as
strncpy() doesn't add it itself.

So in fact to allow a maximum space for string dup of 23, strndup() has
to be called like this:
| dup = strndup(src, 23 - 1);

FIXME: Find the critical points in code this change touches and make
sure the invocation there is correct.

src/common.c

index 41ae7f8..bfb0ae4 100644 (file)
 // use our own strndup() if it's not available
 char *strndup(const char *s, size_t n)
 {
-       if (strlen(s) + 1 > n) {
-               char *ret = malloc(n);
+       if (strlen(s) > n) {
+               char *ret = malloc(n + 1);
                strncpy(ret, s, n);
+               ret[n] = 0;
                return ret;
        } else {
                return strdup(s);