fa.openbsd.tech
[Top] [All Lists]

Re: memdup(3)

Subject: Re: memdup(3)
From: Marco Peereboom <slash@xxxxxxxxxxxx>
Date: Mon, 14 Jul 2008 15:06:58 UTC
Newsgroups: fa.openbsd.tech

On Mon, Jul 14, 2008 at 06:38:49PM +0400, Alexey Dobriyan wrote:
> On Mon, Jul 14, 2008 at 03:06:14PM +0200, Marc Espie wrote:
> > On Mon, Jul 14, 2008 at 04:49:34PM +0400, Alexey Dobriyan wrote:
> > > memdup(3) has strdup(3) semantics but without strings.
> > > 
> > > Canonical code for duplicating buffer looks like:
> > > 
> > >   rpl = malloc(src, len);
> > >   if (!rpl)
> > >           ...
> > >   memcpy(rpl, src, len);
> > > 
> > > Mistakes happen and two lengths in snippet above will be different.
> > > To prevent this memdup(3) was created:
> > > 
> > >   rpl = memdup(src, len);
> > >   if (!rpl)
> > >           ...
> > >   ...
> > 
> > This kind of code is very easy to write. The big question is: do we
> > want it.
> > 
> > That's non-standard stuff, it's not ANSI, it's not POSIX, it's not single
> > unix.
> > 
> > So what's the point ?
> 
> The point is writing "len" once, so it won't diverge from itself.

But you trade an explicit free for and implicit one.  I find this a
confusing interface that adds nothing.  It is also not part of a
standard.

> 
> > It doesn't really help at writing portable code (more the contrary).
> 
> strlcpy() wasn't in ANSI C, POSIX et al when it was created, yet it was
> added to libc and from there spread. Of course, bugs aren't that common
> with malloc+memcpy sequence, but they definitely happen.
> 
> malloc+memcpy sequence exists extracted in quite a few projects.
> Sometimes, under different name, sometimes with different prototype,
> but people definitely use this idiom, so let's help them?
> 
> Plenty of examples in OpenBSD codebase alone.

Sure and they aren't broken.

> 
> > In case you don't know, strdup isn't even in ANSI C, and that's not an
> > oversight.  The design of the standard libc separates strings and memory
> > functions, and you'll notice that strdup combines the two, thus `tying'
> > string handling functions to a specific set of memory allocation.
> > 
> > That, and the fact that historically, strdup is not even well specified,
> > so that if you use strdup in a C++ program, you don't even know how you
> > should free the memory (is it free ? is it delete ? *both* options have
> > existed in the past, courtesy of NeXtStep).


<Prev in Thread] Current Thread [Next in Thread>