cmallocdynamic-memory-allocationfreecalloc

"Memory allocated with calloc must be freed all at once"?


I read that memory allocated with calloc "must be freed all at once".

Does it mean that it's not the case with malloc?

If yes, could someone give me a real world example? Many thanks!


Solution

  • Memory allocated with calloc and malloc is freed the same way: by passing the pointer returned by the allocator to free.

    The confusion might come from the fact that calloc is called with 2 arguments to allocate an array, one argument for the element size and the other for the number of elements. All at once might refer to the fact that the elements cannot not be freed individually, free must be called with a pointer to the initial element, which is the pointer returned by calloc.

    A call to calloc(n1, n2) is semantically equivalent to this:

    #include <limits.h>
    #include <stdlib.h>
    #include <string.h>
    
    void *calloc(size_t n1, size_t n2) {
        if (n1 != 0 && n2 > SIZE_MAX / n1)
            return NULL;
        size_t size = n1 * n2;
        void *p = malloc(size);
        if (p != NULL)
            memset(p, 0, size);
        return p;
    }
    

    Note that in practice the C library's implementation of calloc is smarter than this: it can avoid manually setting the memory to zero if the memory was retrieved via a system call that guarantees zero initialization, and this memory might not even be actually assigned to the process until it is effectively modified. So using calloc for allocation causes very little overhead, allows for simpler initialization and make erroneous code more reproducible, thus easier to debug.