@matheusbsbs / matheus-bagliano / commits / 68d3025a80
Fork 0

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>

Pierre Habouzit committed Sep 15, 2007 at 23:53 UTC 68d3025a805097ec148ec6e9b0b54a5db1ef138e
1 file changed +9 -8
git-compat-util.h
+9 -8
@@ -211,19 +211,20 @@ static inline void *xmalloc(size_t size)
211 return ret;
212 }
213
214 -static inline char *xstrndup(const char *str, size_t len)
214 +static inline void *xmemdupz(const void *data, size_t len)
215 {
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);
218 p[len] = '\0';
219 return p;
220 }
221
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 +
228 static inline void *xrealloc(void *ptr, size_t size)
229 {
230 void *ret = realloc(ptr, size);