[PATCH v4 1/5] Introduce xstrndup function

Masatake YAMATO yamato at redhat.com
Mon Jun 19 03:45:48 UTC 2017


* defs.h (xstrndup): New prototype.
* xmalloc.c (xstrndup): New function.
* configure.ac (AC_CHECK_FUNC): check the avaiabllity of strndup.

Changes in version 4 (suggested by ldv):

	* Use strndup if available.
	* Fix a typo in log.

Signed-off-by: Masatake YAMATO <yamato at redhat.com>
---
 configure.ac |  1 +
 defs.h       |  1 +
 xmalloc.c    | 21 +++++++++++++++++++++
 3 files changed, 23 insertions(+)

diff --git a/configure.ac b/configure.ac
index b4cf4cb..9bf89fc 100644
--- a/configure.ac
+++ b/configure.ac
@@ -282,6 +282,7 @@ AC_CHECK_FUNCS(m4_normalize([
 	readahead
 	signalfd
 	stpcpy
+	strndup
 	strerror
 	strsignal
 	sync_file_range
diff --git a/defs.h b/defs.h
index 8a28e89..5e05457 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 a017620..3ef4856 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;
+}
-- 
2.9.4





More information about the Strace-devel mailing list