Add strndup

Dmitri Nikulin dnikulin at
Wed Jun 21 00:16:33 PDT 2006

On 21 Jun 2006 08:53:37 +0200, Andreas Hauser <andy at xxxxxxxxxxxxxxx> wrote:
dillon wrote @ Tue, 20 Jun 2006 23:27:14 -0700 (PDT):
> :andy wrote @ 20 Jun 2006 21:44:17 +0200:
> :
> :Fixed the off-by-one:
> :
>     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?
Why not call it memdup instead and drop the termination? String
functions for standard C, as broken as they are, are all based around
having a null terminator, and in your case you're actually basing
entirely off a length (but allocating for length + 1 which is very
counter-intuitive). Not that this function really achieves anything to
begin with...
I never cared for C-style strings. To set a length for them you have
to modify them, and this means you have to re-allocate if doing
read-only tokenizing or regex extraction. In my own code I define a
structure containing a length and a pointer, and when extracting
sub-strings, simply set up such a structure defining the scope of the
sub-string. If it needs to be copied out for safe writing, it's
trivial to do, and at no point is there a need to check through for a
null terminator. If the structure itself is on the stack you don't
even need to malloc. The whole thing translates nicely into any kind
of memory usage, and works naturally with buffering data blocks since
you already know the length. Additional plus to being able to store 0
as a valid byte, which apparently matters for some encodings.

Proof of concept implemented as a header of static inline functions.
BSD license, C99, should be WARNS6 clean too. This will probably solve
your problem a lot better than yet another broken string function.
 -- Dmitri Nikulin

More information about the Submit mailing list