malloc() vs calloc(): Key Differences explained with Examples

 malloc() vs calloc(): Key Differences explained with Examples 

What is Dynamic Memory Allocation?

Dynamic memory allocation is a process of allocating memory at run time. There are four library routines, calloc(), free(), realloc(), and malloc() which can be used to allocate memory and free it up during the program execution. These routines are defined in the header file called stdlib.h.

What is malloc() ?

It is a function which is used to allocate a block of memory dynamically. It reserves memory space of specified size and returns the null pointer pointing to the memory location.

The pointer returned is usually of type void. It means that we can assign malloc function to any pointer. The full form of malloc is memory allocation.

In this tutorial, you will learn:

  • What is Dynamic Memory Allocation?

  • What is malloc() ?

  • What is calloc() ?

  • Why use malloc() ?

  • Why use calloc() ?

  • Syntax of malloc()

  • Syntax of calloc()

  • Example of malloc() in C

  • Example of calloc() in C

  • Difference Between calloc() and malloc()

What is calloc() ?

Calloc() function is used to allocate multiple blocks of memory. It is a dynamic memory allocation function which is used to allocate the memory to complex data structures such as arrays and structures. If this function fails to allocate enough space as specified, it returns will null pointer. The full form of calloc function is contiguous allocation. 

 

Why use malloc() ?

Here are the reasons of using malloc()

  • You should use malloc() when you have to allocate memory at runtime.
  • You should use malloc when you have to allocate objects which must exist beyond the execution of the current memory block.
  • Go for malloc() if you need to allocate memory greater than the size of that stack.
  • It returns the pointer to the first byte of allocated space.
  • It enables developers to allocate memory as it is needed in the exact amount.
  • This function allocates a memory block size of bytes from the heap.

Why use calloc() ?

Here are the reasons of using calloc()

  • When you have to set allocated memory to zero.
  • You can use calloc that returns a pointer to get access to memory heap.
  • Used when you need to initialize the elements to zero to returns a pointer to the memory.
  • To prevent overflow that is possible with malloc()
  • Use calloc() to request a page that is known to already be zeroed.

Syntax of malloc()

Here is a Syntax of malloc()

ptr = (cast_type *) malloc (byte_size);

In above syntax, ptr is a pointer of cast_type. The malloc function returns a pointer to the allocated memory of byte_size.

Example: ptr = (int *) malloc (50)

When this statement is successfully executed, a memory space of 50 bytes is reserved. The address of the first byte of reserved space is assigned to the pointer "ptr"of type int.

Syntax of calloc()

Here is a Syntax of malloc()

ptr = (cast_type *) calloc (n, size);

The above syntax is used to allocate n memory blocks of the same size. After the memory space is allocated, all the bytes are initialized to zero. The pointer, which is currently at the first byte of the allocated memory space, is returned.

Example of malloc() in C

In the bellow code, sizeof(*ptr) is used to allocate a memory block of 15 integers. In the printf statement, we are finding the value of the 6th integer.

#include<stdlib.h>
#include<stdio.h>
int main(){
int *ptr;
ptr = malloc(15 * sizeof(*ptr)); 
    if (ptr != NULL) {
      *(ptr + 5) = 480; 
      printf("Value of the 6th integer is %d",*(ptr + 5));
    }
}

Output:

Value of the 6th integer is 480

Example of calloc() in C

The C language program below calculates the sum of the first ten terms. If the pointer value if null, then the memory space will not be allocated. 

For loop is used to iterate the value of a variable "i" and print the sum. Lastly, function free is used to free-up the pointer.

#include <stdio.h>
#include <stdlib.h>
    int main() {
        int i, * ptr, sum = 0;
        ptr = calloc(10, sizeof(int));
        if (ptr == NULL) {
            printf("Error! memory not allocated.");
            exit(0);
        }
        printf("Building and calculating the sequence sum of the first 10 terms \n");
        for (i = 0; i < 10; ++i) { * (ptr + i) = i;
            sum += * (ptr + i);
        }
        printf("Sum = %d", sum);
        free(ptr);
        return 0;
    }

Output:

Building and calculating the sequence sum of the first 10 terms n Sum = 45

Difference Between calloc() and malloc()

Herer are important difference between malloc() and calloc(): 


 

KEY DIFFERENCES:

  • malloc() function returns only starting address and does not make it zero on the other hand, calloc() function returns the starting address and make it zero.
  • In malloc function, number of arguments is 2 while in calloc function, number of argument is 1.
  • malloc() time efficiency is higher than calloc() whereas malloc() is not secure as compared to calloc()
  • malloc does not initialize memory whereas calloc performs memory initialization.

Post a Comment

0 Comments