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

Re: memdup(3)

Subject: Re: memdup(3)
From: Marc Espie <espie@xxxxxxxxx>
Date: Mon, 14 Jul 2008 13:08:22 UTC
Newsgroups: fa.openbsd.tech

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 ? It doesn't really help at writing portable code
(more the contrary).

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>