From: Rusty Russell Date: Fri, 16 Oct 2015 19:42:40 +0000 (+1030) Subject: tal/str: fix error in tal_strndup() X-Git-Url: http://git.ozlabs.org/?p=ccan;a=commitdiff_plain;h=28681e0a15c453e86528ca488415e2220cbe0f0a tal/str: fix error in tal_strndup() It used strlen() on the source, which might not be valid. Signed-off-by: Rusty Russell --- diff --git a/ccan/tal/str/str.c b/ccan/tal/str/str.c index 059817b6..83dac663 100644 --- a/ccan/tal/str/str.c +++ b/ccan/tal/str/str.c @@ -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(). */ - 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, "[]")); diff --git a/ccan/tal/str/test/run-strndup.c b/ccan/tal/str/test/run-strndup.c new file mode 100644 index 00000000..d9673548 --- /dev/null +++ b/ccan/tal/str/test/run-strndup.c @@ -0,0 +1,22 @@ +#include +#include +#include +#include +#include +#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(); +}