bug-gnulib
[Top][All Lists]
Advanced

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

Re: xmemdup0


From: Paul Eggert
Subject: Re: xmemdup0
Date: Fri, 09 May 2008 12:17:53 -0700
User-agent: Gnus/5.11 (Gnus v5.11) Emacs/22.2 (gnu/linux)

Eric Blake <address@hidden> writes:

> Would anyone else be interested in adding xmemdup0 to the xalloc
> module?  In m4, I have several places where I copy blocks of
> arbitrary memory, but want to guarantee that it is NUL-terminated so
> that I can later do things like comparing strlen(ptr) with the
> length to check for the (relatively rare) case of embedded NULs in
> that block of memory.

In the strlen case, wouldn't it be more efficient to look for the NUL
while you're copying the block of memory?  That way, you need to do
only one pass over the source.

> It's more efficient to detect an
> unterminated escape sequence at the end of a block if you can always
> read the byte after a backslash, and only on seeing NUL decide
> whether the sequence was invalid or the string exhausted, compared
> to having to check if the memory block has been exhausted yet for
> every backslash prior to reading the next byte.

That does sound like a win.

> void *
> xmemdup0 (void const *ptr, size_t n)
> {
>   void *result = memcpy (xmalloc (n + 1), ptr, n);

One portability glitch: this local variable should be of type 'char *',
not 'void *'; otherwise the next line is not portable.

>   result[n] = 0;
>   return result;
> }

Anyway, I like this new primitive.  Thanks for suggesting it.




reply via email to

[Prev in Thread] Current Thread [Next in Thread]