Wrapping malloc - C

后端 未结 4 1645
眼角桃花
眼角桃花 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 10:04

    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

    1. leak detection
    2. usage analysis
    3. memory pooling
    4. debugging (like the XMALLOC_POISON)
    5. enforced checking

    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

提交回复
热议问题