Mercurial > hg > dmlib
changeset 744:2726d91e3409
Add implementation of dm_strndup().
author | Matti Hamalainen <ccr@tnsp.org> |
---|---|
date | Sat, 04 May 2013 03:25:29 +0300 |
parents | aba7dde79a04 |
children | ab645f4cb8fa |
files | dmlib.h dmstring.c |
diffstat | 2 files changed, 24 insertions(+), 1 deletions(-) [+] |
line wrap: on
line diff
--- a/dmlib.h Mon Apr 22 17:00:01 2013 +0300 +++ b/dmlib.h Sat May 04 03:25:29 2013 +0300 @@ -390,6 +390,7 @@ const char *dmErrorStr(int error); char * dm_strdup(const char *); +char * dm_strndup(const char *, const size_t n); char * dm_strdup_vprintf(const char *, va_list); char * dm_strdup_printf(const char *, ...);
--- a/dmstring.c Mon Apr 22 17:00:01 2013 +0300 +++ b/dmstring.c Sat May 04 03:25:29 2013 +0300 @@ -1,7 +1,7 @@ #include "dmlib.h" #include <stdarg.h> -/* strdup with a NULL check +/* Implementation of strdup() with a NULL check */ char *dm_strdup(const char *s) { @@ -17,6 +17,28 @@ } +/* Implementation of strndup() with NULL check + */ +char *dm_strndup(const char *s, const size_t n) +{ + char *res; + if (s == NULL) + return NULL; + + size_t len = strlen(s); + if (len > n) + len = n; + + if ((res = dmMalloc(len + 1)) == NULL) + return NULL; + + memcpy(res, s, len); + res[len] = 0; + + return res; +} + + /* Simulate a sprintf() that allocates memory */ char *dm_strdup_vprintf(const char *fmt, va_list args)