Skip to content

Commit

Permalink
Add xmemdupz() that duplicates a block of memory, and NUL terminates it.
Browse files Browse the repository at this point in the history
A lot of places in git's code use code like:

  char *res;

  len = ... find length of an interesting segment in src ...;
  res = xmalloc(len + 1);
  memcpy(res, src, len);
  res[len] = '\0';
  return res;

A new function xmemdupz() captures the allocation, copy and NUL
termination.  Existing xstrndup() is reimplemented in terms of
this new function.

Signed-off-by: Pierre Habouzit <madcoder@debian.org>
Signed-off-by: Junio C Hamano <gitster@pobox.com>
  • Loading branch information
MadCoder authored and gitster committed Sep 18, 2007
1 parent 0557656 commit 68d3025
Showing 1 changed file with 9 additions and 8 deletions.
17 changes: 9 additions & 8 deletions git-compat-util.h
Expand Up @@ -211,19 +211,20 @@ static inline void *xmalloc(size_t size)
return ret;
}

static inline char *xstrndup(const char *str, size_t len)
static inline void *xmemdupz(const void *data, size_t len)
{
char *p;

p = memchr(str, '\0', len);
if (p)
len = p - str;
p = xmalloc(len + 1);
memcpy(p, str, len);
char *p = xmalloc(len + 1);
memcpy(p, data, len);
p[len] = '\0';
return p;
}

static inline char *xstrndup(const char *str, size_t len)
{
char *p = memchr(str, '\0', len);
return xmemdupz(str, p ? p - str : len);
}

static inline void *xrealloc(void *ptr, size_t size)
{
void *ret = realloc(ptr, size);
Expand Down

0 comments on commit 68d3025

Please sign in to comment.