changeset 10040:00a47a592b0a

Add xmemdup0. * 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>
author Eric Blake <ebb9@byu.net>
date Fri, 09 May 2008 13:54:18 -0600
parents 3e891533dd19
children db1d8acdb9c1
files ChangeLog lib/xalloc.h lib/xmalloc.c
diffstat 3 files changed, 33 insertions(+), 1 deletions(-) [+]
line wrap: on
line diff
--- 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.
--- a/lib/xalloc.h
+++ b/lib/xalloc.h
@@ -50,6 +50,7 @@
 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 @@
   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
 
 
--- a/lib/xmalloc.c
+++ b/lib/xmalloc.c
@@ -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 @@
   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 *