mirror of
https://source.denx.de/u-boot/u-boot.git
synced 2026-06-13 15:03:58 +03:00
Merge patch series "add memdup_nul(), use it and memdup() in a few places"
Rasmus Villemoes <ravi@prevas.dk> 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/20260421075439.16696-1-ravi@prevas.dk
This commit is contained in:
55
lib/string.c
55
lib/string.c
@@ -343,41 +343,29 @@ size_t strcspn(const char *s, const char *reject)
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifndef __HAVE_ARCH_STRDUP
|
||||
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;
|
||||
|
||||
if ((s == NULL) ||
|
||||
((new = malloc (strlen(s) + 1)) == NULL) ) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
strcpy (new, s);
|
||||
return new;
|
||||
return s ? memdup_nul(s, strlen(s)) : NULL;
|
||||
}
|
||||
|
||||
char * strndup(const char *s, size_t n)
|
||||
{
|
||||
size_t len;
|
||||
char *new;
|
||||
|
||||
if (s == NULL)
|
||||
return NULL;
|
||||
|
||||
len = strlen(s);
|
||||
|
||||
if (n < len)
|
||||
len = n;
|
||||
|
||||
new = malloc(len + 1);
|
||||
if (new == NULL)
|
||||
return NULL;
|
||||
|
||||
strncpy(new, s, len);
|
||||
new[len] = '\0';
|
||||
|
||||
return new;
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user