From 34ebad3df7a99eea326f9170f2517b5d23873d1b Mon Sep 17 00:00:00 2001 From: Eric Blake Date: Fri, 9 May 2008 13:54:18 -0600 Subject: [PATCH] Add xmemdup0. * lib/xalloc.h (xmemdup0): New prototype and C++ typesafe implementation. * lib/xmalloc.c (xmemdup0): New C implementation. Signed-off-by: Eric Blake --- ChangeLog | 7 +++++++ lib/xalloc.h | 7 +++++++ lib/xmalloc.c | 20 +++++++++++++++++++- 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/ChangeLog b/ChangeLog index 06ca95580..d864de169 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,10 @@ +2008-05-09 Eric Blake + + Add xmemdup0. + * lib/xalloc.h (xmemdup0): New prototype and C++ typesafe + implementation. + * lib/xmalloc.c (xmemdup0): New C implementation. + 2008-05-08 Bruno Haible * m4/wctype.m4 (gl_WCTYPE_H): Correct indentation. diff --git a/lib/xalloc.h b/lib/xalloc.h index 40dcf4bd5..314ed6d19 100644 --- a/lib/xalloc.h +++ b/lib/xalloc.h @@ -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 inline T * +xmemdup0 (T const *p, size_t s) +{ + return (T *) xmemdup0 ((void const *) p, s); +} + # endif diff --git a/lib/xmalloc.c b/lib/xmalloc.c index 3a1234574..b1f6993e3 100644 --- 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 @@ 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 * -- 2.11.0