Table of Contents

    calloc() Function in C: Usage and Examples

    calloc() Function in C: Usage and Examples

    C language inherently does not have any technique to allocate memory dynamically, there are 4 library functions under stdlib.h for dynamic memory allocation.

    Function Use of Function
    malloc() Allocates requested size of bytes and returns a pointer first byte of allocated space
    calloc() Allocates space for an array elements, initializes to zero and then returns a pointer to memory
    free() deallocate the previously allocated space
    realloc() Change the size of previously allocated space

    We already discuss about malloc() function in previous chapter.

    calloc() function

    calloc() is another memory allocation function that is used for allocating memory at runtime. calloc function is normally used for allocating memory to derived data types such as arrays and structures. If it fails to allocate enough space as specified, it returns a NULL pointer.

    calloc() function is also like malloc() function. But calloc() initializes the allocated memory to zero. But, malloc() doesn’t.

    Syntax:

    The syntax of calloc() function is given below:

    #include 
    void *calloc(size_t num, size_t size);
    ptr=(cast-type*)calloc(size_t num, size_t size);  // here ptr is a pointer

    The calloc( ) function allocates memory the size of which is equal to num * size. That is, calloc( ) allocates sufficient memory for an array of num objects of size size. All bits in the allocated memory are initially set to zero.

    Example

    ptr = (float*) calloc(25, sizeof(float));

    This statement allocates contiguous space in memory for an array of 25 elements each of size of float, i.e, 4 bytes.

    free() function in C

    The free( ) function returns the memory pointed to by ptr to the heap. This makes the memory available for future allocation.

    The memory occupied by malloc() or calloc() functions must be released by calling free() function. Otherwise, it will consume memory until program exit.

    Program; realloc() function and allocating address position

    In this program, we are going to allcate some memory using calloc() function.

    #include 
    void free(void *ptr);

    Program

    In this program, we are going to allcate some memory using calloc() function.

    
    #include <stdio.h>
    #include <string.h>
    #include <stdlib.h>
     
    int main()
    {
         char *ptr;
         /* memory is allocated dynamically */
         ptr = calloc( 20, sizeof(char) );
         if( ptr== NULL )
         {
            printf("Couldn't able to allocate requested memory\n");
         }
         else
         {
             strcpy( ptr,"atnyla.com");
         }
             printf("Dynamically allocated memory content : " \
                    "%s\n", ptr );
             free(ptr);
    }
    
    Output
    
    Dynamically allocated memory content : atnyla.com
    Press any key to continue . . .
    

    Program

    In this program we are going to allcate some memory using calloc() function. From the user it will take some elements and it will give the smallest element.

    
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
        int i, n;
        int *ptr;
    
        printf("Enter total number of elements: ");
        scanf("%d", &n);
    
        ptr = (int*) calloc(n,sizeof(int));
    	 /*returns a void pointer(which is type-casted to int*)
            pointing to the first block of the allocated space*/
    
    
    //If it fails to allocate enough space as specified, it returns a NULL pointer.
        if(ptr == NULL)
        {
            printf("Error.Not enough space available");
            exit(0);
        }
    
        for(i=0;i<n;i++)
           scanf("%d",ptr+i); //storing elements from the user in the allocated space
    
        for(i=1;i<n;i++)
        {
           if(*ptr > *(ptr+i))
               *ptr = *(ptr+i);
        }
    
        printf("Smallest element is %d \n",*ptr);
    
        return 0;
    }
    
    Output
    
    Enter total number of elements: 5
    2
    3
    7
    1
    8
    Smallest element is 1
    Press any key to continue . . .
    

    Program

    C program to find sum of n elements entered by user. To perform this program, allocate memory dynamically using calloc() function.

    
    #include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
        int num, i, *ptr, sum = 0;
        printf("Enter number of elements: ");
        scanf("%d", &num);
    
    	// Dynamic memory allocation
        ptr = (int*) calloc(num, sizeof(int));
        if(ptr == NULL)
        {
            printf("Error! memory not allocated.");
            exit(0);
        }
    
        printf("Enter elements of array: \n");
        for(i = 0; i < num; ++i)
        {
            scanf("%d", ptr + i); // takes element from user
            sum += *(ptr + i);
        }
    
        printf("Sum = %d \n", sum); // print sum
        free(ptr);
        return 0;
    }
    
    Output
    
    Enter number of elements: 5
    Enter elements of array:
    1
    2
    3
    4
    5
    Sum = 15
    Press any key to continue . . .
    

    Difference Between malloc() and calloc()

    malloc() calloc()
    It allocates only single block of requested memory It allocates multiple blocks of requested memory
    int *ptr;
    ptr = malloc( 20 * sizeof(int) );
    For the above, 20*4 bytes of memory only allocated in one block. 
    Total = 80 bytes
    int *ptr;
    Ptr = calloc( 20, 20 * sizeof(int) );
    For the above, 20 blocks of memory will be created and each contains 20*4 bytes of memory. 
    Total = 1600 bytes
    malloc () doesn’t initializes the allocated memory. It contains garbage values calloc () initializes the allocated memory to zero
    type cast must be done since this function returns void pointer
    int *ptr;
    ptr = (int*)malloc(sizeof(int)*20 );
    Same as malloc () function
    int *ptr;
    ptr = (int*)calloc( 20, 20 * sizeof(int) );
    Number of argument is 1 Number of arguments is 2