Wrapping malloc - C

后端 未结 4 1639
眼角桃花
眼角桃花 2021-01-02 09:10

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          


        
4条回答
  •  执念已碎
    2021-01-02 09:52

    1. 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.

    2. Don't know.

    3. 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.

提交回复
热议问题