Cyberithub

Dynamic Memory Allocation with malloc(), calloc(), free() and realloc() functions in C

Advertisements

In this tutorial, I will explain the concepts of Dynamic Memory Allocation with malloc(), calloc(), free and realloc() functions in C. Dynamic Memory allocation is a feature introduced in C to allocate memory blocks as per the changing requirement. This is introduced to overcome the limitation of static memory allocation where once the size is decided it cannot be changed later. Also if you are using memory less than the allocated size then it will be a wastage of the rest of the allocated memory.

Hence it is a good idea to use the concepts of Dynamic Memory allocation where you are not aware of the total size of memory you are going to need. This feature of Dynamic Memory allocation is implemented in C by four Standard Library methods declared in the header file <stdlib.h>. Those methods are malloc(), calloc(), realloc() and free(). We will discuss about each of the methods in detail.

How Dynamic Memory Allocation different from Static Memory Allocation

In Static memory allocation, once we allocated the memory it cannot be resized or change like it happens in the case of primitive variable declaration or in array size allocation where memory allocation happens at the compile time and cannot be changed later but in dynamic memory allocation, memory blocks can be resized dynamically at the runtime.

Dynamic Memory Allocation with malloc(), calloc(), free() and realloc() functions in C 2

Dynamic Memory Allocation with malloc(). calloc(), free() and realloc() functions in C

Also Read: 10 Useful Examples of sizeof function in C

1. malloc() function

malloc() is a C library function to dynamically allocate requested size in the heap memory area and returns a pointer to the memory block after successful allocation. More on malloc() Man Page.

Syntax

void *malloc(size_t size)

Parameters

size: it is total size of the memory block in bytes

Example 

[root@localhost ~]# vi allocate.c
#include <stdlib.h>
#include <stdio.h>
main()
{
int *p,n,i,s;
printf("Number of elements are:");
scanf("%d",&n);
p = (int *)malloc(sizeof(int)); //dynamic memory allocation using malloc() method
if(p == NULL)
{
printf("Requested memory not allocated\n");
exit(1);
}
for(i=0;i<n;i++)
{
printf("Enter Elements:");
scanf("%d",p + i);
s += *(p + i);
}
printf("Sum of the Elements is:%d\n",s);
}

Compile Your Program

[root@localhost ~]# gcc -o allocate allocate.c

Run Your Program

[root@localhost ~]# ./allocate
Number of elements are:4
Enter Elements:1
Enter Elements:2
Enter Elements:3
Enter Elements:4
Sum of the Elements is:10

2. calloc() function

Like malloc() function, calloc() is also used to dynamically allocate memory blocks in the Heap memory area but it is different from malloc() in two ways: first calloc() is used to allocate n number of contiguous block of memory instead of just one memory block and the second is that the memory initialized in calloc() is equal to zero as compared to malloc() where memory initialized to some garbage value.

Syntax

void *calloc(size_t n, size_t size);

Parameters

n: total number of memory blocks to be allocated

size: it is the size of each block that needs to be allocated

Example

[root@localhost ~]# vi calloc.c
#include <stdlib.h>
#include <stdio.h>
main()
{
int *p,n,i,s;
printf("Number of elements are:");
scanf("%d",&n);
p = (int *)calloc(n,sizeof(int)); //dynamic memory allocation using calloc() method
if(p == NULL)
{
printf("Requested memory not allocated\n");
exit(1);
}
for(i=0;i<n;i++)
{
printf("Enter Element:");
scanf("%d",p + i);
s += *(p + i);
}
printf("Sum of the Elements are:%d\n",s);
}

Compile Your Program

[root@localhost ~]# gcc -o calloc calloc.c

Run Your Program

[root@localhost ~]# ./calloc
Number of elements are:5
Enter Element:1
Enter Element:2
Enter Element:3
Enter Element:4
Enter Element:5
Sum of the Elements are:15

3. free() function

free() function is used to release the memory allocated by malloc() and calloc() function. Dynamically allocated memory is not going to be released automatically so we have a function available in C Library to help release the memory once the work is completed.

Syntax

void free(void *ptr);

Parameters

ptr: The pointer to the memory block to release.

Example

[root@localhost ~]# vi free.c
#include <stdlib.h>
#include <stdio.h>
main()
{
int *p;
p = (int *)malloc(sizeof(int)); //dynamic memory allocation 
p[4] = 10;
if(p == NULL)
{
printf("Requested memory not allocated\n");
exit(1);
}
printf("Value stored is:%d\n",p[4]);
free(p); //release the allocated memory
p = NULL;
}

Compile Your Program

[root@localhost ~]# gcc -o free free.c

Run Your Program

[root@localhost ~]# ./free
Value stored is:10

4. realloc() function

The realloc() function in C is used to resize the memory block allocated through malloc() and calloc() library function without losing any old data. Failure of this function call will result in return of NULL value.

Syntax

void *realloc(void *ptr, size_t newsize);

Parameters

ptr : it is a pointer pointing to the memory block allocated by malloc() or calloc() method

newsize : the new size of the memory block that needs to be passed

Example

[root@localhost ~]# vi realloc.c
#include <stdlib.h>
#include <stdio.h>
main()
{
int *p,n,i,s;
printf("Number of elements are:");
scanf("%d",&n);
p = (int *)malloc(n); //dynamically allocated memory
if(p == NULL)
{
printf("Requested memory not allocated\n");
exit(1);
}
for(i=0;i<n;i++)
{
printf("Enter Element:");
scanf("%d",p + i);
s += *(p + i);
}
printf("Sum of the Elements are:%d\n",s);
p = (int *)realloc(p,n+1); //new allocated memory block
printf("New Number of Elements are:%d\n",n+1);
for(i=0;i<n+1;i++)
{
printf("Enter Element:");
scanf("%d",p + i);
s += *(p + i);
}
printf("Total Sum of the Elements are:%d\n",s);
}

Compile Your Program

[root@localhost ~]# gcc -o realloc realloc.c

Run Your Program

[root@localhost ~]# ./realloc
Number of elements are:3
Enter Element:1
Enter Element:2
Enter Element:3
Sum of the Elements are:6
New Number of Elements are:4
Enter Element:1
Enter Element:2
Enter Element:3
Enter Element:4
Total Sum of the Elements are:16

 

 

 

 

Popular Recommendations:-

Useful C Program to List Network Interfaces using only 30 Lines of Code

Best Explanation of Wrapper Classes in Java: Autoboxing and Unboxing with Examples

5 Best Ways to Become root user or Superuser in Linux (RHEL/CentOS/Ubuntu)

How to Install PHP on RedHat/CentOS 7 with Easy Steps

7 Easy Steps to Install PHP on RHEL 8/CentOS 8

Easy Steps to Install Java on Ubuntu 20.04

Best Steps to Install Java on RHEL 8/CentOS 8

15 ansible-vault command examples to encrypt and decrypt sensitive data/files on Linux

Leave a Comment