Register Login

Differences between Malloc() and Calloc() Functions with Comparison Chart

Updated Jan 07, 2020

The fundamental difference that exists between malloc and calloc in C language pertains to calloc() requiring two arguments instead of a single argument as needed by malloc(). Both calloc and malloc in C are essential functions of the middle-level programming language. They go along the way in enabling the cause of de-allocation and dynamic memory allocation at run time.

Through this article, we aim to enlighten you about the definition of calloc and malloc, the syntax of calloc and malloc and the key difference between calloc and malloc. We will also discuss the similarities between these two functions and the features of C Dynamic Memory Allocation to enable the cause of your short and long-term C programming needs. Read on for more.

Calloc vs Malloc

If you are still wondering about what is the difference between calloc and malloc, then this table will help you understand the distinctive properties with greater clarity.

Basis of Difference Malloc() Calloc()
No of blocks Malloc() allocates a single block of the memory required in bytes. Calloc() allocates multiple blocks of the requested memory to any process or program dynamically.
Syntax void *malloc(size_t size); void *calloc(size_t num, size_t size);
Initialization the malloc() function fails to initialize and clear out the allocated memory. It contains a random garbage value and the allocated memory item is incapable of being altered. The calloc() function initialises the earlier allocated memory to zero.
Speed The malloc() performs quickly and without any lags. The calloc () is comparatively slow and takes a longer time to complete as it first initialises the value of the pointer to ZERO. However, this lag is minuscule and does not affect the performance of the program in any manner.
Type of memory allocation The malloc() function assigns memory of the desired 'size' from the available heap. The calloc() function assigns memory that is the size of what’s equal to ‘num *size’.
Meaning on name The name malloc is attributed to memory allocation. The name calloc means contiguous allocation.
Returning of pointer void *malloc(size_t n) will return a pointer to get a value of n bytes of uninitialised storage if the request is satisfied. Conversely, it will give it a NULL value if the request fails to be successful. In case the memory space allocated by malloc() gets overrun, then the results will remain as undefined. Void *calloc(size_t n, size_t size) will return a pointer to allocate enough free space of an array of n objects; which will be of a pre-defined and specified size. The NULL value is assigned in case the request fails to be satisfied. Here, the storage is again initialised to zero.
Types of arguments taken Malloc() takes in just one argument – the number of bytes. Calloc() takes in two arguments – the number of blocks as well as the size of every single block.

Definition of Malloc()

The malloc function in C programming language is used for assigning a block of memory as bytes. The programmer is required to give the block size required for use explicitly. The malloc function program refers to the RAM for the user system to enable the cause of memory allocation.

In this case, the malloc function concedes, or in other words, is successful in allocating the desired memory.  A pointer is returned to the block of memory created right in the beginning.

The pointer so returned by the Malloc() function is of the void type. It means that a pointer of any type can be assigned for taking care of the coding needs of the C programmer.

A NULL value is returned in case the malloc() function is unable to assign the amount of memory needed. The malloc function can be accessed in TURBO C via its header file stdlib.h or alloc.h. If you are a coder using the UNIX platform, then the header file <malloc.h> will be useful for your needs.

Syntax of Malloc()

The syntax of the malloc function is:

malloc(number of elements * size of each element);

For instance:

int*ptr;
ptr= malloc(10*sizeof (int)}

Here, size ideally represents the memory size that needs to be allocated in bytes. In other words, it refers to the number of memory locations (contiguous) that have to be allocated in bytes.

However, as mentioned earlier, as the malloc function is known to return a void pointer, the necessity of the cast operator comes into play. A cast operator is needed for transforming the pointer type as returned and based on the coding needs. For instance, the declaration can also be presented as:

ptr_var=(type_cast*) malloc(size)

Here, ptr_var refers to the pointer’s name that still has the first address of the memory block allocated earlier; type_cast refers to the data type that the type void return pointer will be transformed into. The (size) in the malloc syntax describes the allocated memory block size in bytes.

For instance,

int*ptr;
ptr=(int*) malloc (10*size of (int));

Here, the memory allocated by the malloc() will contain garbage value.

This has to be noted to assess if the system RAM has successfully granted the corresponding request that has been generated by malloc for the sake of memory allocation or not. The memory allocation request will be rejected in case there is no space available – the malloc function will return a NULL in case memory has not been allocated.

C program to demonstrate the use of malloc()

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Main Function Starts */

int main () {
    int *a = NULL;
    int sz,i;

    printf("nt Please Enter the size of Array : ");
    scanf("%d",&sz);

    /*Allocation of space and and validation as well*/
    if((a = (int * ) malloc (sz * sizeof (int))) == NULL) {
        fprintf(stderr, "nt Memory allocation failure !!!");
        exit(1); //For abnormal termination ....
    }
    /*To set the bit*/
    memset (a,0, sizeof (int));

    i=0;

    while (i < sz) {
        printf(" %d ", a[i++]);
    }//end of while ...

    putchar ('n');
    return(0);

} //end of main

OUTPUT ::

Please Enter the size of Array : 5                                                                                    

0  0  0  0  0

Definition of calloc()

The calloc function requires two arguments instead of one as used by malloc(). Otherwise, it operates in the same way as malloc(). When calloc is declared for the sake of allocating a block of memory, the assigned region is immediately initialised to zero.

This is not the case with malloc that resists from touching the allocated memory block and its contents. This malloc and calloc difference aptly describe the main attribute of calloc function in C.

Syntax of Calloc()

The C library function

void *calloc(size_t nitems, size_t size)

is used for allocating the requested memory. It is also responsible for returning a pointer to the same. While malloc() does not set the allocated memory to zero, the calloc() does this to set the memory value to zero.

For instance:

int*ptr;
ptr = (int*) calloc(10,2);

Here, figure 2 specifies the data type size in bytes for which the memory allocation has to be made. In this case, two stands for integers. Figure 10 signifies the total number of elements that require memory allocation.

The argument passed in the case of the malloc function was (n*10); it was a single argument that was depicted as a simple expression (this is because no commas were separating any more arguments). This is not the case with the calloc function. This is a significant difference between malloc and calloc in C.

In the calloc() declaration, when the same is executed successfully, a memory block amounting to 20 bytes in size will be allocated to the program requesting the same.

The address given to the first memory block will be allocated to the requesting program. Additionally, the address of the first block will be allocated to the pointer referred to as ptr. The memory space allocated by the calloc function would hold all zeros. This function is available in the header file saved as <alloc.h> or <stdlib.h> in TURBO C.

C program to demonstrate the use of calloc()

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* Main Function Starts */

int main () {
    int *a = NULL;
    int sz,i;

    printf("nt Please Enter the size of Array : ");
    scanf("%d",&sz);
   
    /* Allocation of space and validation as well */
       
        if((a = (int * ) calloc (sz, sizeof(int ))) == NULL) {
            fprintf(stderr, "nt Memory allocation failure !!!");
            exit(1); //For abnormal termination ....
        }//end of of
       
    i=0;
    while (i < sz) {
        printf(" %d ", a[i++]);
    }//end of while ...
   
    if(a != NULL) {
        free (a);
        a = NULL;
    }
   
    putchar ('n');
    return(0);

} //end of main


OUTPUT :

Please Enter the size of Array : 5                                                                                    

0  0  0  0  0

Key difference between Calloc and Malloc

  • There exist two differences between calloc and malloc in terms of C programming languages.
  • The first difference is visible in context to the number of arguments. While malloc() uses a single argument, The calloc() requires two arguments for the completion of its operations.
  • Secondly, the initialisation of allocated memory does not take place in the malloc function. Conversely, the calloc() initialises the value of the allocated memory to zero. The table below chalks out the difference between malloc and calloc in C in detail.

Similarities Between Malloc and Calloc

Both calloc and malloc are utilised for dynamic memory allocation in C language. They are used for obtaining and dynamically allocating memory blocks. The pointer returned by both malloc or calloc has proper alignment with regards to the object in the reckoning. However, they must first be cast into appropriate types for the process to be successful.

By proper alignment, we mean that the value assigned to the returned address will be guaranteed to figure as an even multiple of alignment. Here, the value attributed to the alignment should be a power of two; also, it must either be equal to or greater than the size of a given the word. Yet another similarity is that the calloc() and malloc() functions will fail to be successful in the following cases:

1. If the physical limits defined for the system is exceeded by n memory bytes that cannot be assigned.

2. If adequate memory is not available for the allocation of n bytes of system memory; it becomes possible for the application to try again later.

C Dynamic Memory Allocation

Dynamic memory allocation is an essential and unique feature attributed to C language. It enables programmers to create data structures and types of different sizes and lengths as is suited to the program in the reckoning. Memory allocation relates to the assigning of computer memory to enable the execution of processes and applications. Dynamic allocation techniques are generally used when the coders are not aware of the amount of memory space that will be required for the running of any program and process.

Dynamic memory allocation in C language is attributed to the issues linked with static memory assigning. The reason being that if fewer elements are attached to the memory and saved within the same, then the rest of the allocated memory would go to waste. Therefore, C dynamic memory allocation declarations are used to overcoming the issues of static memory allocation. Herein, the memory is assigned as and when required and not earlier on.

Conclusion

Both these functions in C language - malloc and calloc – are useful for the dynamic allocation of memory space. They have quite a few differences and similarities between them. Additionally, their benefits and disadvantages can be gauged to assess which function would suit a particular C program or process.

For instance, malloc () is faster in comparison to calloc (). More so, malloc() is much easier to put into use as it merely requires one argument. Calloc() takes more time as it first initialises the memory space to ZERO and allocates the required memory to the same. The decision to use calloc or malloc would depend on the need for variable initialisation and how important it is for the performance of your program – take your pick accordingly.

We shall await your comments with regards to more differences between calloc and malloc that we may have missed in the article. Do write back to us.


×