summaryrefslogtreecommitdiff
path: root/lib/string.c
diff options
context:
space:
mode:
authorTom Rini <[email protected]>2026-05-12 15:41:52 -0600
committerTom Rini <[email protected]>2026-05-12 15:41:52 -0600
commite3e651c480c46b332f16a7555b97c6c6fd640a40 (patch)
tree01f7277b103a10ef301e6981d7f4ca2e33f653db /lib/string.c
parent5732bd0f457b4c671e46574d64d4acb099c0f0a5 (diff)
parent8d209186a1e4aca4ec44745d05d51de7e80f7e3e (diff)
Merge patch series "add memdup_nul(), use it and memdup() in a few places"
Rasmus Villemoes <[email protected]> says: There are quite a few places where we allocate X+1 bytes, initialize the first X bytes via memcpy() and then set the last byte to 0. The kernel has a helper for that, kmemdup_nul(). Introduce a similar one, and start making use of it in a few places. Also the existing memdup() helper can be put to more use. There are lots more places one could modify. But for code shared with host tools, one would need to do some refactoring, putting memdup() and memdup_nul() in their own str-util.c TU which could then also be included in the tools build. Link: https://lore.kernel.org/r/[email protected]
Diffstat (limited to 'lib/string.c')
-rw-r--r--lib/string.c51
1 files changed, 18 insertions, 33 deletions
diff --git a/lib/string.c b/lib/string.c
index 302efe048b0..37ea8c29561 100644
--- a/lib/string.c
+++ b/lib/string.c
@@ -343,41 +343,29 @@ size_t strcspn(const char *s, const char *reject)
}
#endif
-#ifndef __HAVE_ARCH_STRDUP
-char * strdup(const char *s)
+void *memdup_nul(const void *src, size_t len)
{
- char *new;
+ char *dst;
- if ((s == NULL) ||
- ((new = malloc (strlen(s) + 1)) == NULL) ) {
+ if (len + 1 < len)
return NULL;
- }
- strcpy (new, s);
- return new;
-}
-
-char * strndup(const char *s, size_t n)
-{
- size_t len;
- char *new;
-
- if (s == NULL)
+ dst = malloc(len + 1);
+ if (!dst)
return NULL;
- len = strlen(s);
-
- if (n < len)
- len = n;
-
- new = malloc(len + 1);
- if (new == NULL)
- return NULL;
+ dst[len] = '\0';
+ return memcpy(dst, src, len);
+}
- strncpy(new, s, len);
- new[len] = '\0';
+char * strdup(const char *s)
+{
+ return s ? memdup_nul(s, strlen(s)) : NULL;
+}
- return new;
+char * strndup(const char *s, size_t n)
+{
+ return s ? memdup_nul(s, strnlen(s, n)) : NULL;
}
/**
@@ -410,7 +398,6 @@ void kfree_const(const void *x)
free((void *)x);
}
-#endif
#ifndef __HAVE_ARCH_STRSPN
/**
@@ -698,17 +685,15 @@ void * memscan(void * addr, int c, size_t size)
}
#endif
-char *memdup(const void *src, size_t len)
+void *memdup(const void *src, size_t len)
{
- char *p;
+ void *p;
p = malloc(len);
if (!p)
return NULL;
- memcpy(p, src, len);
-
- return p;
+ return memcpy(p, src, len);
}
#ifndef __HAVE_ARCH_STRNSTR