[uClibc]strndup implementation

Stefan Soucek ssoucek at coactive.com
Thu Oct 11 02:45:31 UTC 2001


Erik,

This is the most efficient implementation in C I could come up with for
strndup. It calls strlen, malloc and memcpy, though. But with implementing 
strlen and memcpy as loops this adds approx 20 bytes more than with the 
function calls. The whole thing compiles on i386 to about 80 bytes.

/********************** Function strndup
***********************************/

#ifdef L_strndup
char *strndup(const char *str, size_t len)
{
	register size_t n;
	register char *dst;

	n = strlen(str);
	if (len < n)
    	        n = len;
	dst = (char *) malloc(n+1);
	if (dst) {
	        memcpy(dst, str, n);
		dst[n] = '\0';
	}
	return dst;
}
#endif


In addition to the code added to string.c, the external declaration of
strndup in string.h has to be activated (remove #if 0). Also, a
strndup.o must be added to the MOBJ variable in libc/string/Makefile.

-Stefan

> -----Original Message-----
> From: Erik Andersen [mailto:andersen at codepoet.org]
> Sent: Wednesday, October 10, 2001 2:45 PM
> To: Stefan Soucek
> Cc: 'uClibc at uclibc.org'
> Subject: Re: [uClibc]strndup
> 
> 
> On Tue Oct 09, 2001 at 04:00:34PM -0700, Stefan Soucek wrote:
> > Howdy,
> > 
> > I was wondering if uClibc currently supports strndup(). 
> If've looked at the
> > latest string.h and I find that the bottom section where 
> bits/string2.h is
> > included (which has a macro for strndup) is #if-0-ed out. 
> Am I overlooking
> > something here?
> 
> It just needs someone to write one.  The bits/string*.h stuff 
> is commented out
> since it is all inlines which produce big bloated binaries.  
> So if you need a
> strndup, feel free to follow the example of how I've written 
> everything in
> libc/string/string.c.  Something I have tried to do (though 
> not finished) is to
> prevent the string functions from calling other functions.  
> This is because
> most of them are smaller then 50 bytes, and so could (at some 
> future date) be
> added into a small uclibc-static lib so they could always be 
> staticly linked
> and still be a win by eliminating the cost of the elf vector 
> code needed to fix
> up the symbols when dynamically linking.  But that can only 
> be guaranteed to be
> a win of the code is small (~<50bytes) and makes no function calls...
> 
>  -Erik
> 
> --
> Erik B. Andersen   email:  andersen at codepoet-consulting.com
> --This message was written using 73% post-consumer electrons--
> 
> 
> _______________________________________________
> uClibc mailing list
> uClibc at uclibc.org
> http://uclibc.org/mailman/listinfo/uclibc
> 





More information about the uClibc mailing list