Wrapping malloc - C

后端 未结 4 1638
眼角桃花
眼角桃花 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:53

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

提交回复
热议问题