[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
xmemdup0
From: |
Eric Blake |
Subject: |
xmemdup0 |
Date: |
Fri, 9 May 2008 17:51:47 +0000 (UTC) |
User-agent: |
Loom/3.14 (http://gmane.org/) |
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;
}
--
Eric Blake