[PATCH v3 2/5] Introduce xstrndup function

Masatake YAMATO yamato at redhat.com
Tue Jun 13 08:26:42 UTC 2017


* defs.h (xstrndup): New prototypes.
* xmalloc.c (xstrndup): New function.

Signed-off-by: Masatake YAMATO <yamato at redhat.com>
---
 defs.h    |  1 +
 xmalloc.c | 12 ++++++++++++
 2 files changed, 13 insertions(+)

diff --git a/defs.h b/defs.h
index 52f40b3..063394e 100644
--- a/defs.h
+++ b/defs.h
@@ -398,6 +398,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 1158927..c1ff3f5 100644
--- a/xmalloc.c
+++ b/xmalloc.c
@@ -85,3 +85,15 @@ char *xstrdup(const char *str)
 
 	return p;
 }
+
+char *xstrndup(const char *str, size_t n)
+{
+	char *p = xmalloc(n + 1);
+
+	if (!p)
+		die_out_of_memory();
+
+	strncpy(p, str, n);
+	p[n] = '\0';
+	return p;
+}
-- 
2.9.4





More information about the Strace-devel mailing list