Search code examples
cmemoryallocation

What does it mean to initialize memory to zero in C?


I am reading about pointers and dynamic memory allocation in C. I have found that the function calloc() is similar to malloc() but the former does initialize memory to 0.

I do not understand why does it mean to initialize memory to zero?

NOTE: I am not asking the difference between malloc and calloc, but the meaning of initializing memory to zero.

Thanks in advance.


Solution

  • p = calloc(12, 1024);
    

    Is roughly equivalent to:

    p = malloc(12 * 1024);
    if (p != NULL)
        memset(p, 0, 12 * 1024);
    

    So calloc does two things that malloc does not:

    • It multiplies the nmemb and size variables to calculate the total size of the allocation
    • It sets every byte of the allocation to zero

    For this purpose, calloc is good for allocating arrays, particular arrays of scalar values.

    There are cases where this initialization is undesirable:

    • Initialization to all-zero bits is insufficient for pointers, where NULL may not be all zeros.
    • If you're going to use the allocation as a buffer and will be reading data into it, then it's a waste of time to initialize it to all-zeros first.