From eec588b0b2d77eb2fe6d441efb6ab66ed538bedf Mon Sep 17 00:00:00 2001 From: Matthias Andree Date: Sat, 10 Apr 2010 17:49:23 +0200 Subject: Add xstrndup(). --- xmalloc.c | 12 ++++++++++++ xmalloc.h | 6 ++++++ 2 files changed, 18 insertions(+) diff --git a/xmalloc.c b/xmalloc.c index a762d0a2..f722c73b 100644 --- a/xmalloc.c +++ b/xmalloc.c @@ -69,4 +69,16 @@ char *strdup(const char *s) } #endif /* !HAVE_STRDUP */ +char *xstrndup(const char *s, size_t len) +{ + char *p; + size_t l = strlen(s); + + if (len < l) l = len; + p = (char *)xmalloc(l + 1); + memcpy(p, s, l); + p[l] = '\0'; + return p; +} + /* xmalloc.c ends here */ diff --git a/xmalloc.h b/xmalloc.h index 690b5741..81835828 100644 --- a/xmalloc.h +++ b/xmalloc.h @@ -25,4 +25,10 @@ XMALLOCTYPE *xrealloc(/*@null@*/ XMALLOCTYPE *, size_t n); * pointer, abort program on failure. */ char *xstrdup(const char *src); +/** Duplicate at most the first \a n characters from \a src to a newly + * malloc()d memory region and NUL-terminate it, and return its pointer, abort + * program on failure. The memory size is the lesser of either the string + * length including NUL byte or n + 1. */ +char *xstrndup(const char *src, size_t n); + #endif -- cgit v1.2.3