[PATCH v2 4/9] lib/string.c: introduce memdup_nul() helper

Rasmus Villemoes ravi at prevas.dk
Tue Apr 21 09:54:34 CEST 2026


This is completely analogous to the linux kernel's kmemdup_nul()
helper, apart from the lack of the gfp_t argument: Allocate a buffer
of size {len}+1, copy {len} bytes from the given buffer, and add a
final nul byte.

This pattern exists in a number of places, so this helper can reduce
some boilerplate code.

Reviewed-by: Simon Glass <sjg at chromium.org>
Signed-off-by: Rasmus Villemoes <ravi at prevas.dk>
---
 include/linux/string.h | 13 +++++++++++++
 lib/string.c           | 15 +++++++++++++++
 2 files changed, 28 insertions(+)

diff --git a/include/linux/string.h b/include/linux/string.h
index a28150fa578..b2e38ecf26e 100644
--- a/include/linux/string.h
+++ b/include/linux/string.h
@@ -143,6 +143,19 @@ void *memchr_inv(const void *, int, size_t);
  */
 void *memdup(const void *src, size_t len);
 
+/**
+ * memdup_nul() - allocate a buffer and copy in the contents, appending a nul byte
+ *
+ * Note that this returns a valid pointer even if @len is 0
+ *
+ * @src: data to copy in
+ * @len: number of bytes to copy
+ * Return: allocated buffer with the copied contents and an extra nul byte,
+ *      or NULL if not enough memory is available
+ *
+ */
+void *memdup_nul(const void *src, size_t len);
+
 unsigned long ustrtoul(const char *cp, char **endp, unsigned int base);
 unsigned long long ustrtoull(const char *cp, char **endp, unsigned int base);
 
diff --git a/lib/string.c b/lib/string.c
index 2c1baa568b9..3923cce5561 100644
--- a/lib/string.c
+++ b/lib/string.c
@@ -343,6 +343,21 @@ size_t strcspn(const char *s, const char *reject)
 }
 #endif
 
+void *memdup_nul(const void *src, size_t len)
+{
+	char *dst;
+
+	if (len + 1 < len)
+		return NULL;
+
+	dst = malloc(len + 1);
+	if (!dst)
+		return NULL;
+
+	dst[len] = '\0';
+	return memcpy(dst, src, len);
+}
+
 char * strdup(const char *s)
 {
 	char *new;
-- 
2.53.0



More information about the U-Boot mailing list