Add xmemdup0.
authorEric Blake <ebb9@byu.net>
Fri, 9 May 2008 19:54:18 +0000 (13:54 -0600)
committerEric Blake <ebb9@byu.net>
Fri, 9 May 2008 20:01:05 +0000 (14:01 -0600)
* lib/xalloc.h (xmemdup0): New prototype and C++ typesafe
implementation.
* lib/xmalloc.c (xmemdup0): New C implementation.

Signed-off-by: Eric Blake <ebb9@byu.net>
ChangeLog
lib/xalloc.h
lib/xmalloc.c

index 06ca955..d864de1 100644 (file)
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,10 @@
+2008-05-09  Eric Blake  <ebb9@byu.net>
+
+       Add xmemdup0.
+       * lib/xalloc.h (xmemdup0): New prototype and C++ typesafe
+       implementation.
+       * lib/xmalloc.c (xmemdup0): New C implementation.
+
 2008-05-08  Bruno Haible  <bruno@clisp.org>
 
        * m4/wctype.m4 (gl_WCTYPE_H): Correct indentation.
index 40dcf4b..314ed6d 100644 (file)
@@ -50,6 +50,7 @@ void *xcalloc (size_t n, size_t s);
 void *xrealloc (void *p, size_t s);
 void *x2realloc (void *p, size_t *pn);
 void *xmemdup (void const *p, size_t s);
+void *xmemdup0 (void const *p, size_t s);
 char *xstrdup (char const *str);
 
 /* Return 1 if an array of N objects, each of size S, cannot exist due
@@ -264,6 +265,12 @@ xmemdup (T const *p, size_t s)
   return (T *) xmemdup ((void const *) p, s);
 }
 
+template <typename T> inline T *
+xmemdup0 (T const *p, size_t s)
+{
+  return (T *) xmemdup0 ((void const *) p, s);
+}
+
 # endif
 
 
index 3a12345..b1f6993 100644 (file)
@@ -1,7 +1,7 @@
 /* xmalloc.c -- malloc with out of memory checking
 
    Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
-   1999, 2000, 2002, 2003, 2004, 2005, 2006 Free Software Foundation,
+   1999, 2000, 2002, 2003, 2004, 2005, 2006, 2008 Free Software Foundation,
    Inc.
 
    This program is free software: you can redistribute it and/or modify
@@ -113,6 +113,24 @@ xmemdup (void const *p, size_t s)
   return memcpy (xmalloc (s), p, s);
 }
 
+/* Clone an object P of size S, with error checking, and include a
+   terminating NUL byte.
+
+   The terminating NUL makes it safe to use strlen or rawmemchr to
+   check for embedded NUL; it also speeds up algorithms such as escape
+   sequence processing on arbitrary memory, by making it always safe
+   to read the byte after the escape character rather than having to
+   check if each escape character is the last byte in the object.  */
+
+void *
+xmemdup0 (void const *p, size_t s)
+{
+  char *result = xcharalloc (s + 1);
+  memcpy (result, p, s);
+  result[s] = 0;
+  return result;
+}
+
 /* Clone STRING.  */
 
 char *