xstrndup: Use strndup instead of implementing it.

Signed-off-by: Martin Lewis <martin.lewis.x84@gmail.com>
Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
This commit is contained in:
Martin Lewis 2020-03-08 13:35:20 -05:00 committed by Denys Vlasenko
parent 726d0d148b
commit 9b4a9d96b8

@ -93,26 +93,17 @@ char* FAST_FUNC xstrdup(const char *s)
// the (possibly truncated to length n) string into it. // the (possibly truncated to length n) string into it.
char* FAST_FUNC xstrndup(const char *s, int n) char* FAST_FUNC xstrndup(const char *s, int n)
{ {
int m;
char *t; char *t;
if (ENABLE_DEBUG && s == NULL) if (ENABLE_DEBUG && s == NULL)
bb_simple_error_msg_and_die("xstrndup bug"); bb_simple_error_msg_and_die("xstrndup bug");
/* We can just xmalloc(n+1) and strncpy into it, */ t = strndup(s, n);
/* but think about xstrndup("abc", 10000) wastage! */
m = n;
t = (char*) s;
while (m) {
if (!*t) break;
m--;
t++;
}
n -= m;
t = xmalloc(n + 1);
t[n] = '\0';
return memcpy(t, s, n); if (t == NULL)
bb_die_memory_exhausted();
return t;
} }
void* FAST_FUNC xmemdup(const void *s, int n) void* FAST_FUNC xmemdup(const void *s, int n)