aboutsummaryrefslogtreecommitdiffstats
path: root/strndup.c
diff options
context:
space:
mode:
authorMattias Andrée <maandree@kth.se>2018-08-12 21:35:12 +0200
committerMattias Andrée <maandree@kth.se>2018-08-12 21:35:12 +0200
commit93b8428b5812191177c790ea9ffb9158d5a296b4 (patch)
tree8e43220208a7e3b4780a49b8278e731f3b5fcbbf /strndup.c
parentAdd DONT_DEFINE_CLOCK_MONOTONIC_RAW (diff)
downloadlibsimple-93b8428b5812191177c790ea9ffb9158d5a296b4.tar.gz
libsimple-93b8428b5812191177c790ea9ffb9158d5a296b4.tar.bz2
libsimple-93b8428b5812191177c790ea9ffb9158d5a296b4.tar.xz
Add tests
Signed-off-by: Mattias Andrée <maandree@kth.se>
Diffstat (limited to 'strndup.c')
-rw-r--r--strndup.c44
1 files changed, 41 insertions, 3 deletions
diff --git a/strndup.c b/strndup.c
index 12c8006..cc828a5 100644
--- a/strndup.c
+++ b/strndup.c
@@ -3,9 +3,11 @@
char *
-libsimple_strndup(const char *s, size_t n)
+libsimple_strndup(const char *s, size_t n) /* FIXME */
{
- void *ret;
+ char *ret;
+ size_t m = strlen(s);
+ n = MIN(n, m);
if (n == SIZE_MAX) {
errno = ENOMEM;
return NULL;
@@ -13,6 +15,42 @@ libsimple_strndup(const char *s, size_t n)
if (!(ret = malloc(n + 1)))
return NULL;
memcpy(ret, s, n);
- ((char *)ret)[n] = '\0';
+ ret[n] = '\0';
return ret;
}
+
+
+#ifdef TEST
+#include <assert.h>
+
+int
+main(void)
+{
+ const char *s = "test";
+ void *p;
+
+ p = libsimple_memdup(s, 5);
+ assert(p && p != s);
+ assert(!strcmp(p, "test"));
+ memset(p, 0, 5);
+ assert(!strcmp(s, "test"));
+ free(p);
+
+ p = libsimple_memdup(s, 3);
+ assert(p && p != s);
+ assert(!strcmp(p, "tes"));
+ memset(p, 0, 5);
+ assert(!strcmp(s, "test"));
+ free(p);
+
+ p = libsimple_memdup(s, 0);
+ assert(p && p != s);
+ assert(!strcmp(p, ""));
+ memset(p, 0, 5);
+ assert(!strcmp(s, "test"));
+ free(p);
+
+ return 0;
+}
+
+#endif