From: Dagobert Michelsen Date: Fri, 28 Feb 2020 10:36:50 +0000 (+0100) Subject: Fix sstrndup X-Git-Tag: collectd-5.11.0~20^2~2 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=e1a5978e69eaad9850a2ec4f1b27a0792638cbfb;p=thirdparty%2Fcollectd.git Fix sstrndup --- diff --git a/src/utils/common/common.c b/src/utils/common/common.c index bf86ab28b..dd91dabc2 100644 --- a/src/utils/common/common.c +++ b/src/utils/common/common.c @@ -160,6 +160,15 @@ char *sstrdup(const char *s) { return r; } /* char *sstrdup */ +size_t sstrnlen(const char *s, size_t n) { + const char *p = s; + + while(n-- > 0 && *p) + p++; + + return p - s; +} /* size_t sstrnlen */ + char *sstrndup(const char *s, size_t n) { char *r; size_t sz; @@ -167,10 +176,7 @@ char *sstrndup(const char *s, size_t n) { if (s == NULL) return NULL; - sz = strlen(s); - if (sz > n) { - sz = n; - } + sz = sstrnlen(s, n); r = malloc(sz + 1); if (r == NULL) { ERROR("sstrndup: Out of memory."); @@ -180,7 +186,7 @@ char *sstrndup(const char *s, size_t n) { r[sz] = '\0'; return r; -} /* char *sstrdup */ +} /* char *sstrndup */ /* Even though Posix requires "strerror_r" to return an "int", * some systems (e.g. the GNU libc) return a "char *" _and_ diff --git a/src/utils/common/common.h b/src/utils/common/common.h index 7cd8c4c13..fce2d12bb 100644 --- a/src/utils/common/common.h +++ b/src/utils/common/common.h @@ -73,6 +73,7 @@ __attribute__((format(printf, 1, 2))) char *ssnprintf_alloc(char const *format, ...); char *sstrdup(const char *s); +size_t sstrnlen(const char *s, size_t n); char *sstrndup(const char *s, size_t n); void *smalloc(size_t size); char *sstrerror(int errnum, char *buf, size_t buflen);