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(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 1:
The standard does not define the behavior of malloc(0)
. That may return a valid pointer or it may return NULL. Different implementations handle that differently so the code falls back to malloc(1)
to get consistent behavior.
For question 3:
It sets the contents of the buffer to something 'strange'. This way, your code is hopefully not relying on the contents being something specific (which malloc does not guarantee).
For question 2: release_pack_memory is found in sha1_file.c:570.
I am not familiar with this wrapper but here is what its doing
1 - if size=0 was specified then it allocates 1 byte instead if the underlying malloc did not do so
this is presumably done so that a caller can still do free on it (like realloc)
2 I assume its to try to force the underlying memory subsystem to look harder for memory
3 the XMALLOC_POISON forces to buffer to a known state this is common practice in order to prevent and detect odd bugs caused by uninitialized data
Secondly - why do you want to wrap malloc. Start with the idea of what you want to do and then implement it or copy an implementation. Reasons for wrapping malloc
Almost all of these can be done with valgrind - which does much more.
'writing solid code' book has good set of memory wrappers for 1,4 and 5