Add strndup

Matthew Dillon dillon at apollo.backplane.com
Wed Jun 21 01:08:44 PDT 2006


:..
:>     Umm.  That code is broken.  len is only the maximum allowed length,
:>     the actual string may be smaller.
:> 
:>     so e.g. someone might do:  strndup("fubar", 16384).  The returned
:>     string should only be 'fubar\0', and only 6 bytes should be allocated,
:>     not 16384.
:
:But when it works like that, one does not save the strlen.
:Hence i see the dislike for the function.
:I would like to have one, that does not work like that.
:Is there already a name for it?
:
:-- 
:Andy

    You don't save the strlen no matter what.  It's a string function.
    If you want to call it 'strndup' then it has to be compatible with
    the linux strndup() and strndup()'s implementations on other platforms.

    If it isn't taking the length of the string into account, it isn't a
    string function and it shouldn't be called 'str*'.

    In anycase, I wouldn't worry about the strlen().  We are talking 
    a few nanoseconds... maybe 10-20ns for most strings, and strndup()
    is doing a malloc() anyway which is MUCH more expensive then strlen().
    Don't try to over-optimize the functionality at the cost of creating
    obfuscated code!

					-Matt
					Matthew Dillon 
					<dillon at xxxxxxxxxxxxx>





More information about the Submit mailing list