Dynamic Memory Allocation in C using malloc(), calloc()
C Programming c programming notes for gate gate cse c programming questions gate questions on c programming gate study material for cse

Dynamic Memory Allocation in C using malloc( ) and calloc()

Dynamic Memory Allocation in C using malloc() and calloc() function

  • In this Tutorial, we will learn about dynamic memory allocation in C using malloc(), calloc() function.
  • Syntax and the use of different functions for dynamic memory allocation in c have been explained in this Tutorial.
  • The use of malloc(), malloc() , realloc() and free() functions are explained in this Tutorial.

What is Dynamic Memory Allocation in C ?

  • The process of allocating the memory at run time is known as dynamic memory allocation in C.
  • Various built-in functions such are malloc( ), calloc( ) and realloc( ) are used to allocate the memory dynamically
  • free() function is used to release the memory at run time.
  • These functions allocate the memory from Heap (memory area).
  • These functions are declared in stdlib.h header file. We have to include the stdlib.h header file while writing the program for dynamic memory allocation.

Why Dynamic Memory Allocation ?

When we assign memory statically by declaring the array size within the program, thus once we declare the array size before using it.

In this scenario, the memory requirement was fixed. It could not be increased or decreased during the execution of the program.

This type of allocation has a drawback. We cannot predict how much memory will be required.

For Example, if we declare an array like this:

int percentage[20];

Here, we can store percentage information for 20 students. But if we need to store percentage information only for 10 students, memory will be wasted in this case.

There may be another case. Suppose we need to store the percentage for 60 students; in that case, we will have less memory. The solution to these problems is dynamic memory allocation.

It means that with dynamic memory allocation, we can allocate the memory as per our requirements.

Difference between Static and Dynamic Memory Allocation

Difference between dynamic and static memory allocation is as shown in following table.

Static Memory Allocation
Dynamic Memory Allocation
Memory is allotted at compile time
Memory is allotted at run time
Memory cannot be increase during execution of the program
Memory can be increase during execution of the program
Static memory allocation is done using array
Dynamic memory allocation is done using liked list.


dynamic memory allocation in c programming

Dynamic Memory Allocation Functions

C Programming supports various functions which are used for dynamic memory in C. These functions are as follows.

  • malloc()
  • calloc()
  • realloc()
  • free()

Let’s understand each function and how they work one by one.

malloc( ) Function in C

  • malloc() function is used for dynamic memory allocation
  • It allocates requested size bytes and it returns a pointer to the primary byte of the allotted memory space.
  • The malloc() perform returns a pointer of type void. Thus, we can assign it to any pointer.
  • The syntax of the malloc() function is as follows:

         type *ptr ;

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

where ptr may be a pointer of type cast-type.

For Example, the statement

int *x;

x=(int *) malloc(10 *sizeof(int))

This means a memory space of ten times the scale of associate degree int byte is reserved. Therefore, the primary computer memory unit of memory allotted is assigned to the pointer x of int type.

The malloc function can also allocate space for complex data types such as structures. For

ptr= (struct student*) malloc(sizeof (struct student));

Where ptr is a pointer of type struct student.

Program to allocate memory using malloc() function is given below

#include <stdio.h>

#include <stdlib.h>

#include<conio.h>

void main()

{

int n, i, *ptr, sum = 0;

printf(“Enter number of elements: “);

scanf(“%d”, &n);

ptr = (int*) malloc(n * sizeof(int));

// if memory cannot be allocated

if(ptr == NULL)

{

printf(“Error! memory not allocated.”);

exit(0);

}

printf(“Enter elements: “);

for(i = 0; i < n; ++i)

{

scanf(“%d”, ptr + i);

sum += *(ptr + i);

}

printf(“Sum = %d”, sum);

// deallocating the memory

free(ptr);

getch();

}

Output


malloc function in c

 

 

 

 

2. calloc( ) Function

  • calloc() is another memory allocation function that allocates space for an array of items, initializes them to zero, and returns a pointer to the memory.
  • This performance is often used for requesting memory space at run time.
  • The syntax of calloc() function  is as follow:

               ptr= (cast type *) calloc(n, element-size);

This statement allocates contiguous space for n blocks, every of size element-size bytes.

Program for allocating the memory using calloc() function is given below –

#include <stdio.h>

#include <stdlib.h>

int main()

{
int n, i, *ptr, sum = 0;
printf(“Enter number of elements: “);
scanf(“%d”, &n);
ptr = (int*) calloc(n, sizeof(int));
if(ptr == NULL) {
printf(“Error! memory not allocated.”);
exit(0);
}
printf(“Enter elements: “);
for(i = 0; i < n; ++i)
{
scanf(“%d”, ptr + i);
sum += *(ptr + i);
}
printf(“Sum = %d”, sum);
free(ptr);
return 0;
}

Output

Enter number of elements: 5
Enter elements: 12
13
14
15
16
Sum = 70

3.realloc( ) Function

  • realloc() is a memory allocation function that modifies the size of previously allocated space by malloc() and realloc() function.
  • Sometimes the allocated memory space may be larger than what is required or it is less than what is required.
  • In both cases, we can change the memory size already allocated with the realloc function known as reallocation of memory.
  • For example, if the statement does the original allocation.

                           ptr= malloc(size);

then reallocation is done by the statement

                             ptr=realloc(ptr,newsize);

which will allocate a new memory space of size new size to the pointer variable ptr and returns a pointer to the first byte of the new memory block.

Program for realloc() function is given below

#include <stdio.h>
#include <stdlib.h>
#include<conio.h>
void main()

{
int *ptr, i , n1, n2;
clrscr();
printf(“Enter size: “);
scanf(“%d”, &n1);
ptr = (int*) malloc(n1 * sizeof(int));
printf(“Addresses of previously allocated memory:\n”);
for(i = 0; i < n1; ++i)
printf(“%u\n”,ptr + i);
printf(“\nEnter the new size: “);
scanf(“%d”, &n2);
// rellocating the memory
ptr =(int*) realloc(ptr, n2 * sizeof(int));
printf(“Addresses of newly allocated memory:\n”);
for(i = 0; i < n2; ++i)
printf(“%u\n”, ptr + i);
free(ptr);
getch();
}

Output

realloc function

4. free() Function

  • free() function is used with malloc() and calloc() to deallocate the memory allotted by malloc() and calloc() function.
  • Syntax of free() performs as follows.

free(ptr);

Conclusion and Summary

  • In this Tutorial, we have discussed Dynamic memory allocation in C Programming. How to allocate memory dynamically in C.
  • Various memory allocation functions such as malloc() , malloc (), and realloc() have been explained in this Tutorial with Examples and programs.

 

Leave a Reply

Your email address will not be published. Required fields are marked *