C standard library function – calloc()

In case of static memory allocation there are some drawbacks like: wastage of memory, less flexibility, permanent allocation of variables etc. To overcome these situations the concept of Dynamic Memory Allocation has been introduced. In dynamic memory allocation the memories can be allocated dynamically at run time.

There 4 library functions that are described under <stdlib.h> (Standard Library Functions)

1. malloc()
2. calloc()
3. realloc()
4. free()

In this article we’ll thoroughly learn about calloc().

What is calloc()?

Calloc stands for Contiguous Allocation. To allocate memory dynamically we also use the function which is called as calloc() function. calloc() function on success returns the base address of the array and every memory location will be initialized to 0. Whereas in malloc() it was initialized by a garbage value.

Like malloc(), memory allocation fails if sufficient memory is not provided. Unsuccessful memory allocation returns a NULL pointer (nullptr) to the pointer.

Syntax:

ptr = (data_type *)calloc(number_of_elements, element_size);


For example, ptr=(int *)calloc(10, sizeof(int)) will create an array of 10 elements dynamically and will return the base address of the array to ptr. Every memory location will be initialized to 0.

This above statement will allocate 40 bytes of memory. If space is insufficient then the allocation fails and NULL value is returned.

Example

/* C program to understand how calloc() works in DMA */
/* www.codewindow.in */
 
#include <stdio.h>
#include <stdlib.h>
 
// Driver code
int main() {
    int n, i;  
    int *p;   // Integer pointer is declared
     
    printf("Enter a valid range: ");
    scanf("%d", &n);
     
    p=(int *)calloc(10, sizeof(int))   // An int array of n elements has been assigned to the pointer
     
    if(p == NULL) {                  // Checking if memory allocation is successful or not
        printf("\nMemory allocation unsuccessful");
        exit(0);
    }
    else {                          // Else memory allocation is successful
        printf("\nMemory allocation successful");
        printf("\nEnter the elements of array: ");
     
        for(i=0; i<n; ++i)
            scanf("%d", p+i);   // Array elements are taken as input
     
        printf("\nElements of the array are: ");
        for(i=0; i<n; i++)
            printf("%d ", *(p+i));  // Print element of the array
    }
    return 0;
}

Input

Enter a valid range: 10
Enter the elements of array: 1 2 3 4 5 6 7 8 9 10 

Output

Memory allocation successful
Elements of the array are: 1 2 3 4 5 6 7 8 9 10 

Follow Us


You Missed

Also Checkout