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 <ilari.liusvaara@elisanet.fi> Signed-off-by: Junio C Hamano <gitster@pobox.com>
This commit is contained in:
parent
35eabd1579
commit
5bf9219d01
@ -343,6 +343,7 @@ extern void release_pack_memory(size_t, int);
|
|||||||
|
|
||||||
extern char *xstrdup(const char *str);
|
extern char *xstrdup(const char *str);
|
||||||
extern void *xmalloc(size_t size);
|
extern void *xmalloc(size_t size);
|
||||||
|
extern void *xmallocz(size_t size);
|
||||||
extern void *xmemdupz(const void *data, size_t len);
|
extern void *xmemdupz(const void *data, size_t len);
|
||||||
extern char *xstrndup(const char *str, size_t len);
|
extern char *xstrndup(const char *str, size_t len);
|
||||||
extern void *xrealloc(void *ptr, size_t size);
|
extern void *xrealloc(void *ptr, size_t size);
|
||||||
|
15
wrapper.c
15
wrapper.c
@ -34,6 +34,16 @@ void *xmalloc(size_t size)
|
|||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void *xmallocz(size_t size)
|
||||||
|
{
|
||||||
|
void *ret;
|
||||||
|
if (size + 1 < size)
|
||||||
|
die("Data too large to fit into virtual memory space.");
|
||||||
|
ret = xmalloc(size + 1);
|
||||||
|
((char*)ret)[size] = 0;
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* xmemdupz() allocates (len + 1) bytes of memory, duplicates "len" bytes of
|
* xmemdupz() allocates (len + 1) bytes of memory, duplicates "len" bytes of
|
||||||
* "data" to the allocated memory, zero terminates the allocated memory,
|
* "data" to the allocated memory, zero terminates the allocated memory,
|
||||||
@ -42,10 +52,7 @@ void *xmalloc(size_t size)
|
|||||||
*/
|
*/
|
||||||
void *xmemdupz(const void *data, size_t len)
|
void *xmemdupz(const void *data, size_t len)
|
||||||
{
|
{
|
||||||
char *p = xmalloc(len + 1);
|
return memcpy(xmallocz(len), data, len);
|
||||||
memcpy(p, data, len);
|
|
||||||
p[len] = '\0';
|
|
||||||
return p;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
char *xstrndup(const char *str, size_t len)
|
char *xstrndup(const char *str, size_t len)
|
||||||
|
Loading…
Reference in New Issue
Block a user