• Articles
  • Tutorials
  • Interview Questions

Difference Between Malloc and Calloc with Examples

Difference Between Malloc and Calloc with Examples

Both malloc and calloc are library functions used for a process where a program can request and use memory space from the system during program runtime. malloc() is used when you don’t want to initialize, whereas calloc is used when you need zero-initialized memory. Let’s thoroughly understand the difference between malloc and calloc.

malloc() and calloc() are library functions used for dynamic memory allocation where a program can request and use memory during its execution. In this blog, we will do an in-depth comparison between malloc() and calloc(). We have also discussed examples of both of these functions, which will help you understand when to use calloc and malloc while writing a program in C.

Table of Contents

Watch the video below to understand C programming in detail:

Video Thumbnail

What is Dynamic Memory Allocation?

Dynamic memory allocation refers to the process of allocating memory during a program’s execution that allows the program to request memory as needed. In static memory allocation, memory is allocated at compile-time (like when declaring an array with a fixed size).

In other terms, Dynamic memory is like getting extra chairs for a party while the party is happening, allowing you to adjust based on the number of guests. In contrast, static memory is like deciding on the exact number of chairs you’ll need before the party starts, and you can’t change it during the event.

What is malloc()?

malloc() stands for memory allocation. ‘malloc()’ is used to allocate a specified number of bytes of memory. It takes the size of the memory (in bytes) as an argument and returns a pointer to the allocated memory block. This dynamic memory allocation is done on the heap, which is a region of the computer’s memory that is used for storing dynamically allocated data.

Syntax of malloc():

 ptr = (cast-type*) malloc(byte-size);

Example:

 int *ptr;

ptr = (int *)malloc(5 * sizeof(int));  // Allocates memory for 5 integers

What is calloc()? 

calloc() stands for contiguous allocation, is a standard library function in C programming that is used for dynamic memory allocation. It is typically used to allocate memory for an array of elements, initializing all the allocated bytes to zero. 

The calloc() function takes two parameters: the number of elements to allocate memory for, and the size (in bytes) of each element.

           Syntax of calloc():

           ptr = (cast-type*)calloc(n, element-size);
           // here, n is the number of elements, and ‘element-size’ is the size of each element.

 Example:

    int *ptr;

    ptr = (int *)calloc(5, sizeof(int)); // Allocates memory for 5 integers and initializes to 0

One thing that must be taken care of while using malloc() and calloc() is that it is important to free the allocated memory using the ‘free()’ function once that allocated memory is no longer needed to prevent memory leaks. 

Difference Between Malloc and Calloc

Let’s now understand their differences with the help of this comparison table:

Feature Malloc Calloc
Purpose Allocates a single block of memory of a specified size Allocates a specified amount of memory and initializes it to zeros
Syntax ptr = (cast-type*) malloc(byte-size); ptr = (cast-type*)calloc(n, element-size);
Number of Arguments 1 (size of memory block) 2 (number of elements, size of each element)
Memory Initialization No initialization; contains garbage values Sets all bytes to zero
Performance Faster Slower due to the extra initialization step
Typical Use Cases Allocating memory for individual variables, structures, or dynamic arrays Allocating memory for arrays of primitive data types (int, char, etc.)
Memory Leaks More prone to leaks if not explicitly cleared with free() function Less prone to leaks, as initial zeros often indicate uninitialized memory
Error Handling Returns NULL on failure Same as malloc (returns NULL on failure)
Security Considerations Reading uninitialized memory can lead to unexpected behavior Initializing to zeros can offer a layer of security by preventing accidental access to sensitive data

For small allocations, malloc might be slightly faster due to its simpler implementation.

But for larger allocations, calloc can be advantageous for security and preventing memory leaks.

Example of Malloc and Calloc

Here are examples that demonstrate the use of ‘malloc()’ and ‘calloc()’ in C to allocate memory for an array of integers. Both programs demonstrate allocating memory for an array of 5 integers using ‘malloc()’ and ‘calloc()’, respectively. The values printed after allocation will be different because ‘malloc()’ will display uninitialized values, while ‘calloc()’ will show zeros due to its initialization step:

Example of ‘malloc()’: 

#include <stdio.h>
#include <stdlib.h>
int main() {
    int *ptr_malloc;
    int size = 5;
    // Using malloc to allocate memory for 5 integers
    ptr_malloc = (int *)malloc(size * sizeof(int));
    if (ptr_malloc == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }
    printf("Memory allocated using malloc:\n");
    for (int i = 0; i < size; ++i) {
  // Accessing and printing the values in the allocated memory (not initialized)
        printf("%d ", ptr_malloc[I]);
    }
    // Freeing the allocated memory
    free(ptr_malloc);
    return 0;
}
Example of 'malloc()'

Example of ‘calloc()’:

#include <stdio.h>
#include <stdlib.h>
int main() {
    int *ptr_calloc;
    int size = 5;
    // Using calloc to allocate memory for 5 integers
    ptr_calloc = (int *)calloc(size, sizeof(int));
    if (ptr_calloc == NULL) {
        printf("Memory allocation failed\n");
        return 1;
    }
    printf("Memory allocated using calloc (initialized to 0):\n");
    for (int i = 0; i < size; ++i) {
        // Accessing and printing the values in the allocated memory (initialized to 0)
        printf("%d ", ptr_calloc[I]);
    }
    // Freeing the allocated memory
    free(ptr_calloc);
    return 0;
}
Example of

Conclusion

In summary, both ‘malloc()’ and ‘calloc()’ are functions used in C (and C++) for dynamic memory allocation. The key difference is in their initialization behavior: ‘malloc()’ allocates memory without initialization, containing random values, while ‘calloc()’ not only allocates memory but also initializes it to zeros. The choice between calloc and malloc depends on whether zero-initialized memory is needed or not. This offers flexibility in managing memory in C programming with the help of different initialization requirements.

Course Schedule

Name Date Details
Python Course 14 Dec 2024(Sat-Sun) Weekend Batch View Details
21 Dec 2024(Sat-Sun) Weekend Batch
28 Dec 2024(Sat-Sun) Weekend Batch

About the Author

Senior Consultant Analytics & Data Science

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration. 

Full Stack Development