bug-gnulib
[Top][All Lists]
Advanced

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

Re: xmemdup0


From: Jim Meyering
Subject: Re: xmemdup0
Date: Fri, 09 May 2008 20:30:14 +0200

Eric Blake <address@hidden> wrote:

> 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.  Another use case for guaranteeing
> the terminating NUL is in algorithms such as replacing backslash escape
> sequences in regex replacement blocks (since the gnulib regex module can
> already handle embedded NUL transparently).  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.
>
> /* Allocate N + 1 bytes, copy N bytes from PTR, and NUL-terminate the result.
>    Call xalloc_die on failure.
>    In C++, the return type matches PTR, with any const removed.  */
> void *
> xmemdup0 (void const *ptr, size_t n)
> {
>   void *result = memcpy (xmalloc (n + 1), ptr, n);
>   result[n] = 0;
>   return result;
> }

Sounds worthy to me.
For future readers, it'd be nice to check in some
of your justification as a comment or doc.




reply via email to

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