From: Dagobert Michelsen Date: Tue, 25 Feb 2020 14:23:14 +0000 (+0100) Subject: Add sstrndup to common.c X-Git-Tag: collectd-5.11.0~20^2~4 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=81f7ee8a42317147e2bf3929017bd46e854ab82c;p=thirdparty%2Fcollectd.git Add sstrndup to common.c --- diff --git a/src/utils/common/common.c b/src/utils/common/common.c index 2cebc0d5f..bf86ab28b 100644 --- a/src/utils/common/common.c +++ b/src/utils/common/common.c @@ -160,6 +160,28 @@ char *sstrdup(const char *s) { return r; } /* char *sstrdup */ +char *sstrndup(const char *s, size_t n) { + char *r; + size_t sz; + + if (s == NULL) + return NULL; + + sz = strlen(s); + if (sz > n) { + sz = n; + } + r = malloc(sz + 1); + if (r == NULL) { + ERROR("sstrndup: Out of memory."); + exit(3); + } + memcpy(r, s, sz); + r[sz] = '\0'; + + return r; +} /* char *sstrdup */ + /* Even though Posix requires "strerror_r" to return an "int", * some systems (e.g. the GNU libc) return a "char *" _and_ * ignore the second argument ... -tokkee */ diff --git a/src/utils/common/common.h b/src/utils/common/common.h index 4e2eceda7..7cd8c4c13 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); +char *sstrndup(const char *s, size_t n); void *smalloc(size_t size); char *sstrerror(int errnum, char *buf, size_t buflen);