DragonFly BSD
DragonFly submit List (threaded) for 2006-06
[Date Prev][Date Next]  [Thread Prev][Thread Next]  [Date Index][Thread Index]

Re: Add strndup


From: Matthew Dillon <dillon@xxxxxxxxxxxxxxxxxxxx>
Date: Wed, 21 Jun 2006 01:06:22 -0700 (PDT)

:..
:>     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@xxxxxxxxxxxxx>



[Date Prev][Date Next]  [Thread Prev][Thread Next]  [Date Index][Thread Index]