string: tidy up strndup()

It decreases code size:
   text    data     bss     dec     hex filename
    161       0       0     161      a1 strndup-BEFORE.o
    153       0       0     153      99 strndup-AFTER.o

Signed-off-by: André Goddard Rosa <andre.goddard@gmail.com>
This commit is contained in:
André Goddard Rosa 2010-01-30 22:29:59 -02:00
parent 30a419afc3
commit aba3ee7d32

View File

@ -31,12 +31,14 @@
char* strndup(const char* s, size_t n)
{
size_t slen = (size_t)strlen(s);
int len = slen < n ? slen : n;
char* copy = malloc(len+1);
char* copy;
if (slen < n)
n = slen;
copy = malloc(n+1);
if (copy) {
memcpy( copy, s, len );
copy[len] = 0;
memcpy(copy, s, n);
copy[n] = 0;
}
return copy;
}