]> git.ipfire.org Git - thirdparty/u-boot.git/commitdiff
lib/string.c: introduce memdup_nul() helper
authorRasmus Villemoes <ravi@prevas.dk>
Tue, 21 Apr 2026 07:54:34 +0000 (09:54 +0200)
committerTom Rini <trini@konsulko.com>
Tue, 12 May 2026 21:38:00 +0000 (15:38 -0600)
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@chromium.org>
Signed-off-by: Rasmus Villemoes <ravi@prevas.dk>
include/linux/string.h
lib/string.c

index a28150fa5781d06243fadbc6c979fe7aa7123c19..b2e38ecf26e4326732777cbd2987712f9fd1799b 100644 (file)
@@ -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);
 
index 2c1baa568b97a7baac7efa49d0a4e66214dfc7c6..3923cce5561a1fec612abbde0d351e7adc7d10fb 100644 (file)
@@ -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;