From: Masatake YAMATO Date: Tue, 13 Jun 2017 08:26:42 +0000 (+0900) Subject: Introduce xstrndup function X-Git-Tag: v4.18~66 X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=d10d64820f3d61331022c3f44d2f035b65ef86ec;p=strace Introduce xstrndup function * configure.ac (AC_CHECK_FUNCS): Add strndup. * defs.h (xstrndup): New prototype. * xmalloc.c (xstrndup): New function. Signed-off-by: Masatake YAMATO Signed-off-by: Dmitry V. Levin --- diff --git a/configure.ac b/configure.ac index b4cf4cb2..d510f41e 100644 --- a/configure.ac +++ b/configure.ac @@ -283,6 +283,7 @@ AC_CHECK_FUNCS(m4_normalize([ signalfd stpcpy strerror + strndup strsignal sync_file_range utimensat diff --git a/defs.h b/defs.h index 8a28e896..5e054577 100644 --- a/defs.h +++ b/defs.h @@ -401,6 +401,7 @@ void *xcalloc(size_t nmemb, size_t size) void *xreallocarray(void *ptr, size_t nmemb, size_t size) ATTRIBUTE_ALLOC_SIZE((2, 3)); char *xstrdup(const char *str) ATTRIBUTE_MALLOC; +char *xstrndup(const char *str, size_t n) ATTRIBUTE_MALLOC; extern int read_int_from_file(const char *, int *); diff --git a/xmalloc.c b/xmalloc.c index a0176200..3ef48567 100644 --- a/xmalloc.c +++ b/xmalloc.c @@ -85,3 +85,24 @@ char *xstrdup(const char *str) return p; } + +char *xstrndup(const char *str, size_t n) +{ + char *p; + +#ifdef HAVE_STRNDUP + p = strndup(str, n); +#else + p = xmalloc(n + 1); +#endif + + if (!p) + die_out_of_memory(); + +#ifndef HAVE_STRNDUP + strncpy(p, str, n); + p[n] = '\0'; +#endif + + return p; +}