calloc() Function in C Library with Program EXAMPLE

โšก Smart Summary

calloc() in C reserves multiple contiguous blocks of memory on the heap and initializes every byte to zero, returning a void pointer that lets programs create clean, ready-to-use arrays and data structures at runtime.

  • ๐Ÿง  Zero-initialized memory: calloc() clears every allocated byte to zero, unlike malloc() which leaves unpredictable garbage values.
  • ๐Ÿ“ฆ Two arguments: calloc(n, size) reserves n blocks of the given size in one contiguous region.
  • โš ๏ธ NULL check: A failed allocation returns a NULL pointer, so validate the result before using it.
  • ๐Ÿ†š calloc vs malloc: Choose calloc() for clean zeroed arrays and malloc() when speed matters more than initialization.
  • ๐Ÿงน Free the memory: Release every calloc() block with free() to prevent memory leaks.
  • ๐Ÿค– AI assistance: AI assistants and GitHub Copilot draft calloc() calls and flag missing free() statements.

calloc() Function in C

What is calloc in C?

The calloc() in C is a function used to allocate multiple blocks of memory having the same size. It is a dynamic memory allocation function that allocates the memory space to complex data structures such as arrays and structures and returns a void pointer to the memory. Calloc stands for contiguous allocation.

Malloc function is used to allocate a single block of memory space while the calloc function in C is used to allocate multiple blocks of memory space. Each block allocated by the calloc in C programming is of the same size.

Why Use calloc() in C?

Ordinary variables and fixed-size arrays lock their dimensions when the program is compiled, which wastes space when fewer elements are needed and fails outright when more are required. calloc() removes that limit by reserving memory at runtime and, unlike malloc(), it clears every byte to zero before handing the block back. This makes calloc() the natural choice whenever a program needs a clean, predictable region of memory for an array or structure whose size is known only while the code is running.

Dynamic allocation with calloc() fits several common situations:

  • Numeric arrays that should start at zero, such as counters, histograms, or running accumulators.
  • Data structures where leftover garbage values would cause subtle, hard-to-trace bugs.
  • Buffers whose length depends on user input or a file read while the program runs.
  • Blocks too large for the limited stack, since calloc() draws from the much larger heap.

Because the reserved block is contiguous and already zeroed, it can be treated immediately as a ready-to-use array without a separate initialization loop.

calloc() Syntax:

ptr = (cast_type *) calloc (n, size);
  • The above statement example of calloc in C is used to allocate n memory blocks of the same size.
  • After the memory space is allocated, then all the bytes are initialized to zero.
  • The pointer which is currently at the first byte of the allocated memory space is returned.

Whenever there is an error allocating memory space such as the shortage of memory, then a null pointer is returned as shown in the below calloc example.

How to use calloc

The below calloc program in C calculates the sum of an arithmetic sequence.

#include <stdio.h>
    int main() {
        int i, * ptr, sum = 0;
        ptr = calloc(10, sizeof(int));
        if (ptr == NULL) {
            printf("Error! memory not allocated.");
            exit(0);
        }
        printf("Building and calculating the sequence sum of the first 10 terms \ n ");
        for (i = 0; i < 10; ++i) { * (ptr + i) = i;
            sum += * (ptr + i);
        }
        printf("Sum = %d", sum);
        free(ptr);
        return 0;
    }

Result of the calloc in C example:

 
Building and calculating the sequence sum of the first 10 terms
Sum = 45

Difference Between calloc() and malloc()

calloc() and malloc() both reserve memory on the heap and both return a void pointer, or NULL on failure, yet they differ in three practical ways that decide which one to use.

  • Initialization: calloc() sets every byte in the new block to zero, while malloc() leaves the contents uninitialized, so a malloc() block holds unpredictable garbage until the program writes to it.
  • Arguments: calloc() takes two arguments, the number of elements and the size of each, written calloc(n, size); malloc() takes a single argument, the total number of bytes, written malloc(n * size).
  • Speed: malloc() is marginally faster because it skips the zeroing step, which is why code that immediately overwrites the memory often prefers it.

Both functions are declared in stdlib.h and both release their memory with the same free() function. Choose calloc() when a clean, zeroed block matters, and malloc() when raw speed is preferred and the program handles initialization itself.

How to Free Memory Allocated by calloc()

Memory reserved by calloc() lives on the heap and is never released automatically. When a program keeps allocating without freeing, it slowly consumes all available memory, a defect known as a memory leak. The free() function returns a finished block to the system so the space can be reused by later allocations.

The free() function takes a single argument, the pointer that calloc() returned, and releases the entire block at once:

int *ptr;
ptr = calloc(10, sizeof(int));
if (ptr != NULL) {
    /* use the allocated memory here */
    free(ptr);   /* release the block */
    ptr = NULL;  /* avoid a dangling pointer */
}

Follow these rules to manage calloc() memory safely:

  • Call free() exactly once for every successful calloc(); freeing the same block twice causes undefined behavior.
  • Set the pointer to NULL after freeing so it cannot be reused as a dangling pointer.
  • Never free() a pointer that calloc() did not return, including one shifted by pointer arithmetic.
  • Match every allocation with a release before the pointer goes out of scope.

Because calloc() and malloc() both draw from the same heap, the freeing discipline is identical for either function: one free() for each successful allocation, and no access to the block afterward. Keeping allocation and release in balance is the core habit of manual memory management in C, and it prevents both leaks and the crashes caused by reusing memory that has already been returned.

FAQs

calloc() is declared in the standard library header stdlib.h, so add #include <stdlib.h> at the top of the source file. Without it, the compiler may warn about an implicit declaration and misread the returned pointer.

When the heap cannot satisfy the request, calloc() returns a NULL pointer instead of a valid address. Always compare the result against NULL before using it, because dereferencing NULL causes undefined behavior and usually crashes the program.

Yes. calloc() works with any type, including structs and arrays of structs, by passing the element count and sizeof(struct). Every member is zeroed, which gives a clean starting state without a manual initialization loop.

Yes. realloc() accepts any pointer returned by calloc() or malloc() and grows or shrinks the block, preserving existing data. New bytes added by realloc() are not zeroed, so initialize them yourself if needed.

The result is implementation-defined: calloc() may return NULL or a unique pointer that cannot be dereferenced but can safely be passed to free(). Treat either outcome as โ€œno usable memoryโ€ and avoid reading from it.

calloc() reserves one continuous region large enough for all requested elements, so they sit back to back like array cells. The name reflects this contiguous, cleared block, letting pointer arithmetic step through the memory reliably.

Yes. AI coding assistants draft calloc() calls, add NULL checks, and flag missing free() calls or leaks, and they explain pointer arithmetic. Always compile and test the generated code before trusting it in production.

GitHub Copilot suggests calloc(), sizeof(), and matching free() lines from a comment describing your intent. Review each suggestion for missing NULL checks and leaks before you compile.

Summarize this post with: