dillon at apollo.backplane.com
Wed Jun 21 01:14:09 PDT 2006
::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?
: 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!
I need to amend this comment, because I implied that strlen() had to
be taken. In fact, it's a bit more complex then that. strndup() is
not allowed to scan the string beyond the specified maximum length
(because the string might not be terminated, as would be the case if
strndup() were used to cut out strings from a memory-mapped file).
So in this case strndup() would have to be implemented like this:
strndup(const char *src, size_t n)
for (len = 0; len < n && s[len]; ++len) /* bounded strlen */
dst = malloc(len + 1);
bcopy(src, dst, len);
dst[len] = 0;
<dillon at xxxxxxxxxxxxx>
More information about the Submit