Search code examples
cmalloccalloc

Does calloc zero out the entire allocation?


The calloc function in C is used to allocate zeroed memory capable of holding at least the requested amount of elements of a specified size. In practice, most memory allocators may allocate a bigger block in order to increase efficiency and minimize fragmentation. The actual usable block size of an allocation in such systems is usually discoverable by means of special functions, i.e. _msize or malloc_usable_size.

Will calloc make sure the entire usable block is zeroed, or will it only zero the requested count*size part of the allocation?


Solution

  • It depends on the implementation. The standard does not require it to zero more than the requested memory size.

    The standard says:

    Synopsis

    #include <stdlib.h>
    void *calloc(size_t nmemb, size_t size);
    

    Description

    The calloc function allocates space for an array of nmemb objects, each of whose size is size. The space is initialized to all bits zero.

    I would say that it is pretty clear that this does not enforce zeroing anything except the space you have requested in the calloc call.

    This is from an existing implementation:

    PTR memset (PTR dest, register int val, register size_t len) {
      register unsigned char *ptr = (unsigned char*)dest;
      while (len-- > 0)
        *ptr++ = val;
      return dest;
    }
    
    void bzero (void *to, size_t count) {
      memset (to, 0, count);
    }
    
    PTR calloc (size_t nelem, size_t elsize) {
      register PTR ptr;  
      if (nelem == 0 || elsize == 0)
        nelem = elsize = 1;
    
      ptr = malloc (nelem * elsize);
      if (ptr) bzero (ptr, nelem * elsize);
    
      return ptr;
    }
    

    It does only zero the memory you have requested. Other implementations may do it differently.