Navratri Sale: Get Upto 30% OFF on Live Training! Offer Ending in
D
H
M
S
Get Now
How to Dynamically Allocate Memory using calloc() in C?

How to Dynamically Allocate Memory using calloc() in C?

27 May 2024
Advanced
1.48K Views
14 min read
Learn via Video Course & by Doing Hands-on Labs

Free C Programming Online Course With Certificate

calloc() Function in C

calloc() function in C is one of the powerful functions used for Dynamic Memory Allocation in C programming. It is defined inside stdlib.h header file. It allocates multiple blocks of memory with the same size for each block.

In this C Tutorial, we'll try to understand calloc() function in C language, the syntax of calloc() function in C, the advantages and disadvantages of calloc() function in C, and much more. Before that, do check out what is malloc() function in C, and if you're a beginner to C, get enrolled in our C Programming Certification Training to learn from scratch.

Read More: Top 50 Mostly Asked C Interview Questions and Answers

What is calloc() in C?

calloc() is one of those functions used in dynamically allocating memory in C programming. Firstly, 'calloc' stands for 'contiguous allocation' and it is used to allocate memory for arrays, it allocates memory in specified sizes and then initializes that allocated block of memory to zero.

Syntax of calloc() Function in C

The simple syntax of calloc() function in C looks like this:

void *calloc(size_t num_elements, size_t element_size);

Parameters of calloc() Function in C

Here, in the above syntax the parameters are as foolows:
  • num_elements- Elements that need memory to be allocated for are represented by num_elements parameter.
  • element_size- The size is represented by element_size. The size will be in bytes.
  • size_t- It is an integer type that is unsigned and it can hold the size of any object in bytes.

Return Value of calloc() Function in C

The return value of calloc() function depends on whether the procedure was successful or not.
  1. If the memory was successfully allocated, it returns a pointer to the block of that memory.
  2. If the memory allocation fails by any chance, it will return NULL.

Read More: Beginner's Guide to C Programming

Calloc() Function in C library with EXAMPLE

Let's try to understand the application of calloc() function in C library. Look at this example program in C Compiler:
#include <stdio.h>
#include <stdlib.h>

int main() {
    int *arr;
    int num_elements = 5;
    
    // Allocating memory for an array of 5 integers
    arr = (int *)calloc(num_elements, sizeof(int));
    
    if (arr == NULL) {
        fprintf(stderr, "Memory allocation failed\n");
        return 1; // Return error code
    }
    
    // Printing the allocated array (should be initialized to zero)
    printf("Allocated array:\n");
    for (int i = 0; i < num_elements; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    
    // Modifying the elements of the array
    for (int i = 0; i < num_elements; i++) {
        arr[i] = i + 1;
    }
    
    // Printing the modified array
    printf("Modified array:\n");
    for (int i = 0; i < num_elements; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
    
    // Freeing the allocated memory
    free(arr);
    
    return 0; // Return success code
}

Explanation:

In the above program,
  • We have used calloc() function for allocating memory of a 5 integer array.
  • An integer pointer arr was defined earlier, we use it to check if the allocation was successful or not.
  • We have then printed the allocated array, it will have all zeros at initial point due to the factor that calloc() initialises memory to zero. After modifying it will show the new values.
  • At last, we have to free up the memory that was allocated with the help of free() function.

Output

Allocated array:
0 0 0 0 0 
Modified array:
1 2 3 4 5 

Advantages of Calloc() in C Programming

The key advantages of using calloc() function in C programming are as follows:
  1. A major advantage of using calloc() function is that the allocated block of memory is initialized to zero. The reason why initialization is important is that it makes sure that the memory is in a consistent state and is predictable.
  2. With the help of calloc() function, developers can easily allocate memory for arrays without the need to initialize each element to zero so it is best for memory allocation of arrays.
  3. There is no risk of accessing an initialized memory as calloc() already provides initialization to zero.
  4. Error handling is easier with the help of calloc() as it will return NULL if the allocation process fails so the failures can be easily checked and handled.
  5. calloc() also provides cross platform compatibility and is available in mostly all C implementations.

Disadvantages of Calloc() in C Programming

  1. The automatic initialization in calloc() function makes it slower as compared to other functions such as malloc().
  2. The initial allocation of memory to zero leads to wastage of memory usage, which might not be the case in functions that require manual initialization which can be done only when needed.
  3. It is limited to only arrays for memory allocation.
  4. Error handling is, many a times, a complex process while working with calloc().

Difference Between Static and Dynamic Memory Allocation

Static Memory AllocationDynamic Memory Allocation
In static memory allocation, memory allocation happens at compile time.In dynamic memory allocation, memory allocation happens during the execution of the program.
Usually, compiler is the one that automatically handles the memory management.Developers need to manually allocate and deallocate memory with the help of functions like malloc(), calloc(), realloc(), free().
The value of variables remains throughout the execution of the program.The blocks of memory are created and destroyed as per the requirement.
It is comparatively faster in terms of performance.The performance is slower due to manual allocation and deallocation process.
Static allocation provides variables with global scope or file scope.Dynamic memory allocation allows for various scopes based on its usage and accessibility.

Program to check Dynamic Memory Allocation using calloc() function

We can check that dynamic memory is allocated successfully using calloc() function. Here's an example in C code editor:
#include <stdio.h>
#include <stdlib.h>

int main() {
    int *ptr;
    int num_elements = 5;

    // Allocate memory using calloc
    ptr = (int *)calloc(num_elements, sizeof(int));

    // Check if memory allocation was successful
    if (ptr == NULL) {
        printf("Memory allocation failed\n");
    } else {
        printf("Memory allocated successfully\n");

        // Use the allocated memory
        for (int i = 0; i < num_elements; i++) {
            ptr[i] = i + 1; // Assign values to the allocated memory
        }

        // Print the allocated memory values
        printf("Allocated memory values:\n");
        for (int i = 0; i < num_elements; i++) {
            printf("%d ", ptr[i]);
        }
        printf("\n");

        // Free the allocated memory
        free(ptr);
        printf("Memory freed successfully\n");
    }

    return 0;
}

Explanation:

  • In the above program, we have used calloc() to allocate memory for a 5 integer array.
  • We have already defined an integer pointer ptr to check if allocation was successful or not by checking if ptr is 'NULL'.
  • If it was successful, we can use the allocated memory to assign values and print.
  • Finally, using free()function we have freed the allocated memory.

Output

Memory allocated successfully
Allocated memory values:
1 2 3 4 5 
Memory freed successfully

Program to demonstrate the use of the calloc() function

Here is a simple program to print the sum of values entered by the user, that will show you how you can use calloc() function in your program.
#include <stdio.h>
#include <stdlib.h>

int main() {
    int *arr;
    int num_elements, sum = 0;

    // Ask the user to enter the number of elements
    printf("Enter the number of elements: ");
    scanf("%d", &num_elements);

    // Allocate memory for an array of integers using calloc
    arr = (int *)calloc(num_elements, sizeof(int));

    // Check if memory allocation was successful
    if (arr == NULL) {
        printf("Memory allocation failed\n");
        return 1; // Return error code
    }

    // Ask the user to enter the elements of the array
    printf("Enter %d elements:\n", num_elements);
    for (int i = 0; i < num_elements; i++) {
        scanf("%d", &arr[i]);
    }

    // Compute the sum of the elements
    for (int i = 0; i < num_elements; i++) {
        sum += arr[i];
    }

    // Print the sum of the elements
    printf("Sum of the elements: %d\n", sum);

    // Free the allocated memory
    free(arr);

    return 0; // Return success code
}

Output

Enter the number of elements: 5
Enter 5 elements:
10
20
30
40
50
Sum of the elements: 150
Summary
Through this article, we tried to delve deeper into usage and application of the calloc() function in C programming, its advantages and disadvantages. We also learnt how to check if the allocation was success or a fail. For more knowledge of different C concepts, consider enrolling in our C Programming Certification Course.

FAQs

Q1. What is malloc () and calloc () in C?

malloc() and calloc() in C are functions that are used to dynamically allocate memory where, malloc() allocates memory without initializing and calloc() allocates memory initializing it to zero.

Q2. What is calloc syntax?

The syntax for calloc() in C is like this:
void *calloc(size_t num_elements, size_t element_size);
where num_elements is the number of elements and element_size is its size in bytes.

Q3. When to use calloc in C?

You can use calloc() in C when you want to perform dynamic memory allocation for arrays and initialize it to 0.

Q4. Is calloc faster than malloc?

calloc() is not considered faster than malloc() as it allocates the memory with also initializing it to zero and malloc() doesn't initializes.

Q5. What is malloc and calloc in C with example?

Both malloc() and calloc() are functions that are used for dynamic memory allocation in C. For example,
int *ptr1 = (int *)malloc(5 * sizeof(int)); // Allocates memory for an array of 5 integers
int *ptr2 = (int *)calloc(5, sizeof(int)); // Allocates memory for an array of 5 integers initialized to zero
Share Article

Live Classes Schedule

Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
Angular Certification TrainingOct 13SAT, SUN
Filling Fast
08:30PM to 10:30PM (IST)
Get Details
Full-Stack .NET Developer Certification TrainingOct 13SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details
ASP.NET Core ProjectOct 19SAT, SUN
Filling Fast
10:00AM to 12:00PM (IST)
Get Details
Advanced Full-Stack .NET Developer Certification TrainingOct 20SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
.NET Solution Architect Certification TrainingOct 20SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
.NET Microservices Certification TrainingOct 20SAT, SUN
Filling Fast
05:30PM to 07:30PM (IST)
Get Details
ASP.NET Core Certification TrainingOct 20SAT, SUN
Filling Fast
09:30AM to 11:30AM (IST)
Get Details
Microsoft Azure Cloud Architect with AINov 10SAT, SUN
Filling Fast
07:00AM to 09:00AM (IST)
Get Details

Can't find convenient schedule? Let us know

About Author
Sakshi Dhameja (Author and Mentor)

She is passionate about different technologies like JavaScript, React, HTML, CSS, Node.js etc. and likes to share knowledge with the developer community. She holds strong learning skills in keeping herself updated with the changing technologies in her area as well as other technologies like Core Java, Python and Cloud.

Accept cookies & close this