changeset 81:c9c0541bed90

Add th_strndup().
author Matti Hamalainen <ccr@tnsp.org>
date Sat, 04 May 2013 03:38:55 +0300
parents 12f1af4ffc6d
children 3e5c0615125c
files th_string.c th_string.h
diffstat 2 files changed, 18 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/th_string.c	Sat May 04 03:38:41 2013 +0300
+++ b/th_string.c	Sat May 04 03:38:55 2013 +0300
@@ -25,11 +25,27 @@
 }
 
 
+/* Implementation of strndup() with NULL check
+ */
+char *th_strndup(const char *s, const size_t n)
 {
+    char *res;
+    size_t len;
 
+    if (s == NULL)
+        return NULL;
 
+    len = strlen(s);
+    if (len > n)
+        len = n;
 
+    if ((res = th_alloc(len + 1)) == NULL)
+        return NULL;
 
+    memcpy(res, s, len);
+    res[len] = 0;
+
+    return res;
 }
 
 
--- a/th_string.h	Sat May 04 03:38:41 2013 +0300
+++ b/th_string.h	Sat May 04 03:38:55 2013 +0300
@@ -43,6 +43,8 @@
 /* Normal NUL-terminated string functions
  */
 char    *th_strdup(const char *);
+char    *th_strndup(const char *, const size_t);
+
 int     th_strcasecmp(const char *, const char *);
 int     th_strncasecmp(const char *, const char *, size_t);
 void    th_strip_ctrlchars(char *);