]> git.ozlabs.org Git - ccan/commitdiff
tal/str: fix error in tal_strndup()
authorRusty Russell <rusty@rustcorp.com.au>
Fri, 16 Oct 2015 19:42:40 +0000 (06:12 +1030)
committerRusty Russell <rusty@rustcorp.com.au>
Fri, 16 Oct 2015 19:42:40 +0000 (06:12 +1030)
It used strlen() on the source, which might not be valid.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
ccan/tal/str/str.c
ccan/tal/str/test/run-strndup.c [new file with mode: 0644]

index 059817b6aa7e928b8e9ceeef372e2510b6ebd3f3..83dac663f7175d6c95a21a17f3337f61e26aebc0 100644 (file)
@@ -26,11 +26,9 @@ char *tal_strndup(const tal_t *ctx, const char *p, size_t n)
        char *ret;
 
        /* We have to let through NULL for take(). */
        char *ret;
 
        /* We have to let through NULL for take(). */
-       if (likely(p)) {
-               len = strlen(p);
-               if (len > n)
-                       len = n;
-       } else
+       if (likely(p))
+               len = strnlen(p, n);
+       else
                len = n;
 
        ret = tal_dup_(ctx, p, 1, len, 1, false, TAL_LABEL(char, "[]"));
                len = n;
 
        ret = tal_dup_(ctx, p, 1, len, 1, false, TAL_LABEL(char, "[]"));
diff --git a/ccan/tal/str/test/run-strndup.c b/ccan/tal/str/test/run-strndup.c
new file mode 100644 (file)
index 0000000..d967354
--- /dev/null
@@ -0,0 +1,22 @@
+#include <ccan/tal/str/str.h>
+#include <stdlib.h>
+#include <stdio.h>
+#include <ccan/tal/str/str.c>
+#include <ccan/tap/tap.h>
+#include "helper.h"
+
+int main(int argc, char *argv[])
+{
+       char *str, *copy;
+
+       plan_tests(1);
+       str = malloc(5);
+       memcpy(str, "hello", 5);
+       /* We should be fine to strndup src without nul terminator. */
+       copy = tal_strndup(NULL, str, 5);
+       ok1(!strcmp(copy, "hello"));
+       tal_free(copy);
+       free(str);
+
+       return exit_status();
+}