Skip to content

Commit 5bf9219

Browse files
Ilari Liusvaaragitster
authored andcommitted
Add xmallocz()
Add routine for allocating NUL-terminated memory block without risking integer overflow in addition of +1 for NUL byte. [jc: with suggestion from Bill Lear] Signed-off-by: Ilari Liusvaara <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 35eabd1 commit 5bf9219

File tree

2 files changed

+12
-4
lines changed

2 files changed

+12
-4
lines changed

git-compat-util.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -343,6 +343,7 @@ extern void release_pack_memory(size_t, int);
343343

344344
extern char *xstrdup(const char *str);
345345
extern void *xmalloc(size_t size);
346+
extern void *xmallocz(size_t size);
346347
extern void *xmemdupz(const void *data, size_t len);
347348
extern char *xstrndup(const char *str, size_t len);
348349
extern void *xrealloc(void *ptr, size_t size);

wrapper.c

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,16 @@ void *xmalloc(size_t size)
3434
return ret;
3535
}
3636

37+
void *xmallocz(size_t size)
38+
{
39+
void *ret;
40+
if (size + 1 < size)
41+
die("Data too large to fit into virtual memory space.");
42+
ret = xmalloc(size + 1);
43+
((char*)ret)[size] = 0;
44+
return ret;
45+
}
46+
3747
/*
3848
* xmemdupz() allocates (len + 1) bytes of memory, duplicates "len" bytes of
3949
* "data" to the allocated memory, zero terminates the allocated memory,
@@ -42,10 +52,7 @@ void *xmalloc(size_t size)
4252
*/
4353
void *xmemdupz(const void *data, size_t len)
4454
{
45-
char *p = xmalloc(len + 1);
46-
memcpy(p, data, len);
47-
p[len] = '\0';
48-
return p;
55+
return memcpy(xmallocz(len), data, len);
4956
}
5057

5158
char *xstrndup(const char *str, size_t len)

0 commit comments

Comments
 (0)