Skip to content

Commit 68d3025

Browse files
MadCodergitster
authored andcommitted
Add xmemdupz() that duplicates a block of memory, and NUL terminates it.
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>
1 parent 0557656 commit 68d3025

File tree

1 file changed

+9
-8
lines changed

1 file changed

+9
-8
lines changed

git-compat-util.h

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -211,19 +211,20 @@ static inline void *xmalloc(size_t size)
211211
return ret;
212212
}
213213

214-
static inline char *xstrndup(const char *str, size_t len)
214+
static inline void *xmemdupz(const void *data, size_t len)
215215
{
216-
char *p;
217-
218-
p = memchr(str, '\0', len);
219-
if (p)
220-
len = p - str;
221-
p = xmalloc(len + 1);
222-
memcpy(p, str, len);
216+
char *p = xmalloc(len + 1);
217+
memcpy(p, data, len);
223218
p[len] = '\0';
224219
return p;
225220
}
226221

222+
static inline char *xstrndup(const char *str, size_t len)
223+
{
224+
char *p = memchr(str, '\0', len);
225+
return xmemdupz(str, p ? p - str : len);
226+
}
227+
227228
static inline void *xrealloc(void *ptr, size_t size)
228229
{
229230
void *ret = realloc(ptr, size);

0 commit comments

Comments
 (0)