]> git.ipfire.org Git - thirdparty/collectd.git/commitdiff
Add sstrndup to common.c
authorDagobert Michelsen <dam@opencsw.org>
Tue, 25 Feb 2020 14:23:14 +0000 (15:23 +0100)
committerDagobert Michelsen <dam@opencsw.org>
Tue, 25 Feb 2020 14:23:14 +0000 (15:23 +0100)
src/utils/common/common.c
src/utils/common/common.h

index 2cebc0d5f067f4627114bcf962e33936b6d41c93..bf86ab28b985f01f1a5dbf352dab2fb3158f87db 100644 (file)
@@ -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 */
index 4e2eceda7cb948bb86c3a2128cbdb26f64868157..7cd8c4c1301ef7de7883c0f893c5634e3925acb6 100644 (file)
@@ -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);