Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrapping malloc - C

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

  1. I couldn't understand why are they using malloc(1)?
  2. What does release_pack_memory does and I can't find this functions implementation in the whole source code.
  3. What does the #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.

like image 902
Navaneeth K N Avatar asked Mar 19 '10 18:03

Navaneeth K N


People also ask

Can you override malloc?

Overriding the standard malloc can be done either dynamically or statically.

What is malloc () in C?

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.


2 Answers

  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.

like image 157
Lars Avatar answered Oct 21 '22 03:10

Lars


For question 2: release_pack_memory is found in sha1_file.c:570.

like image 28
AKX Avatar answered Oct 21 '22 03:10

AKX