I am a beginner in C. While reading git's source code, I found this wrapper function around malloc
.
void *xmalloc(size_t size)
{
void *ret = malloc(size);
if (!ret && !size)
ret = malloc(1);
if (!ret) {
release_pack_memory(size, -1);
ret = malloc(size);
if (!ret && !size)
ret = malloc(1);
if (!ret)
die("Out of memory, malloc failed");
}
#ifdef XMALLOC_POISON
memset(ret, 0xA5, size);
#endif
return ret;
}
Questions
malloc(1)
?release_pack_memory
does and I can't find this functions implementation in the whole source code.#ifdef XMALLOC_POISON memset(ret, 0xA5, size);
does?I am planning to reuse this function on my project. Is this a good wrapper around malloc
?
Any help would be great.
Overriding the standard malloc can be done either dynamically or statically.
What is malloc() in C? malloc() is a library function that allows C to allocate memory dynamically from the heap. The heap is an area of memory where something is stored. malloc() is part of stdlib. h and to be able to use it you need to use #include <stdlib.
malloc(0) does not work on all a platforms, in which case a one-byte allocation is made instead. Allowing the allocation of 0-length memory blocks simplifies the higher-level logic of the program.
Don't know.
By filling the allocated memory with a non-zero value, it is easier to find bugs in the program where the memory is used without proper initialization: the program will crash almost immediately in such cases. As filling the memory takes time, it is wrapped in a preprocessor define, so it is compiled in only when desired.
For question 2: release_pack_memory is found in sha1_file.c:570.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With