diff th_string.c @ 81:c9c0541bed90

Add th_strndup().
author Matti Hamalainen <ccr@tnsp.org>
date Sat, 04 May 2013 03:38:55 +0300
parents 12f1af4ffc6d
children 3e5c0615125c
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;
 }