From 19a3cad692c232538263cf452859198d5b1af661 Mon Sep 17 00:00:00 2001 From: =?utf8?q?Vladim=C3=ADr=20=C4=8Cun=C3=A1t?= Date: Thu, 15 Nov 2018 18:13:35 +0100 Subject: [PATCH] lib/utils kr_inaddr_str(): avoid another copy ... and avoid a scan-build error. --- lib/utils.c | 25 +++++++++++-------------- lib/utils.h | 2 +- 2 files changed, 12 insertions(+), 15 deletions(-) diff --git a/lib/utils.c b/lib/utils.c index 678cec22b..9a7a69e6f 100644 --- a/lib/utils.c +++ b/lib/utils.c @@ -424,27 +424,24 @@ void kr_inaddr_set_port(struct sockaddr *addr, uint16_t port) int kr_inaddr_str(const struct sockaddr *addr, char *buf, size_t *buflen) { - int ret = kr_ok(); if (!addr || !buf || !buflen) { return kr_error(EINVAL); } - char str[INET6_ADDRSTRLEN + 6]; - if (!inet_ntop(addr->sa_family, kr_inaddr(addr), str, sizeof(str))) { + if (!inet_ntop(addr->sa_family, kr_inaddr(addr), buf, *buflen)) { return kr_error(errno); } - int len = strlen(str); - str[len] = '#'; - u16tostr((uint8_t *)&str[len + 1], kr_inaddr_port(addr)); - len += 6; - str[len] = 0; - if (len >= *buflen) { - ret = kr_error(ENOSPC); - } else { - memcpy(buf, str, len + 1); + const int len = strlen(buf); + const int len_need = len + 1 + 5 + 1; + if (len_need > *buflen) { + *buflen = len_need; + return kr_error(ENOSPC); } - *buflen = len; - return ret; + *buflen = len_need; + buf[len] = '#'; + u16tostr((uint8_t *)&buf[len + 1], kr_inaddr_port(addr)); + buf[len_need - 1] = 0; + return kr_ok(); } int kr_straddr_family(const char *addr) diff --git a/lib/utils.h b/lib/utils.h index db6f5317a..b61b4f76c 100644 --- a/lib/utils.h +++ b/lib/utils.h @@ -393,7 +393,7 @@ static inline char *kr_straddr(const struct sockaddr *addr) { assert(addr != NULL); /* We are the sinle-threaded application */ - static char str[INET6_ADDRSTRLEN + 6]; + static char str[INET6_ADDRSTRLEN + 1 + 5 + 1]; size_t len = sizeof(str); int ret = kr_inaddr_str(addr, str, &len); return ret != kr_ok() || len == 0 ? NULL : str; -- 2.47.3