diff options
author | Mattias Andrée <maandree@kth.se> | 2018-08-12 21:35:12 +0200 |
---|---|---|
committer | Mattias Andrée <maandree@kth.se> | 2018-08-12 21:35:12 +0200 |
commit | 93b8428b5812191177c790ea9ffb9158d5a296b4 (patch) | |
tree | 8e43220208a7e3b4780a49b8278e731f3b5fcbbf /strndup.c | |
parent | Add DONT_DEFINE_CLOCK_MONOTONIC_RAW (diff) | |
download | libsimple-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.c | 44 |
1 files changed, 41 insertions, 3 deletions
@@ -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 |