Dynamic Memory Allocation in C

TIn this tutorial, You will come to know all about the memory allocation that is done in the C programming language while writing programs. 

In this tutorial, You will also come to know about the types of memory allocation in C. There are two types of memory allocation namely static memory allocation and dynamic memory allocation.



Dynamic Memory Allocation in C using 4 functions


Dynamic Memory allocation refers to allocating memory to the variable at run time so that the size of the variable can be changed at runtime according to the user's need. 

There are two types of memory allocation that is done in C programming language inside the programs. Static memory allocation(SMA) is done with the help of a variable while Dynamic memory allocation(DMA) is done with the help of a pointer.
  1. Static Memory allocation (SMA)
  2. Dynamic Memory allocation(DMA)

Static Memory Allocation in C

This memory allocation is done at the compile-time and is fixed in nature i.e., the size given to the variables cannot be changed during the execution of the program. for example array.


Example: static memory allocation in array



#include<stdio.h>
void main() 
 {   
  int a, arrayone[7]; 
  
  printf("Enter 7 values: \n");   

  for(a=0; a<7; a++)   
   {   
    scanf("%d", &arrayone[a]);   
   }   

  printf("Printing the array: \n");   

  for(a=0; a<7; a++)   
   {   
    printf("%d", arrayone[a]);   
   }   
 }


Output


Enter 8 values:
10
-5
2
100
58
23
-90
51
Printing the array:
10
-5
2
100
58
23
-90
51



Dynamic Memory Allocation in C 


Dynamic Memory allocation refers to allocating memory to the variable at run time so that the size of the variable can be changed at runtime according to the user's need. 

Dynamic memory allocation is done at the run time of the program and is flexible in nature. The size of the variable can be modified according to the program and the allocation of this program can be done by the following four functions.


Dynamic memory allocation(DMA) is done with the help of a pointer because the four functions that are used in DMA (calloc, malloc, realloc, free) works on the concept of the pointer.

  1. malloc()
  2. calloc()
  3. realloc()
  4. free()
All the four functions written above are defined in the stdlib header file. The user has to include the stdlib header file while using calloc(), malloc(), realloc() and free() functions.

malloc() in c

malloc() function reserves a block of memory of a specified number of bytes. malloc stands for memory allocation. It returns a pointer of void type so that the user can typecast it into whatever the pointer they want.

If the users want to work on integer pointer then they can typecast it into integer pointer type and if the users want to work with char pointer then they can typecast it into character type pointer.

malloc() function takes a single argument i.e, it takes size and returns a void pointer. It does not initialize the block of memory and return a NULL pointer if the allocation fails.

malloc() function is similar to calloc() function but it does not only allocate the memory but also able to make the partition in different-different sizes. 

For this, a structure data type is used and that is why it only takes one argument i.e; the size of the memory needs to allocate. 

Syntax: 
ptr = (dataType *)malloc(byte_size);
for example:
ptr1 = (int *)malloc(5*sizeof(int));
ptr2 = (char *)malloc(6*sizeof(char));

Example: malloc() function in c


#include<stdio.h>
#include<stdlib.h>
void main() 
 {   
  int *ptr, n, i;  
 
  printf("Enter number of elements: \n"); 
  scanf("%d", &n);

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

  if (ptr == NULL)
   {
    printf("Allocation Failed \n");
    exit(0);
   }

  else
   {
    for(i=0; i<n; i++)
     {
      scanf("%d", ptr+i);
     }
   }

  printf("Elements are: \n");

  for(i=0; i<n; i++)
   {
    printf("%d \n", *(ptr+i));
   }

  free(ptr);
 }


Output



Enter number of elements:
15
2
45
63
21
66
20
35
57
66
50
44
55
35
40
5
Elements are:
2
45
63
21
66
20
35
57
66
50
44
55
35
40
5


calloc() in c

calloc stands for contiguous allocation. It reserves a number of blocks in memory and initializes every byte with 0. It returns a NULL pointer when the allocation of memory fails.

calloc function is used for allocating multiple blocks of memory and initializes it with 0. It takes two arguments (number and byte_size) and returns a void pointer.

calloc() takes two arguments viz., number of blocks and size of each block. Accordingly, it allocates the memory and returns the address of the same and since the address is of void types.

So, the user needs to typecast it into some datatypes and this depends upon the datatypes of the pointer the user is taking to keep this address. 

Syntax: 

ptr = (dataType *)calloc(n, element_size);        // n is no. of blocks
for example:
ptr1 = (int *)calloc(5, sizeof(int));
ptr2 = (char *)calloc(6, sizeof(char));


Example: calloc() function in c


#include<stdio.h>
#include<stdlib.h>
void main()
 {   
  int *pntr, n, i;

  printf("Enter number of elements: \n"); 
  scanf("%d", &n);

  pntr = (int *)calloc(n, sizeof(int));

  if (pntr == NULL)
   {
    printf("Allocation Failed \n");
    exit(0);
   }

  else
   {
    for(i=0; i<n; i++)
     {
      scanf("%d", pntr+i);
     }
   }

  printf("Elements are: \n");

  for(i=0; i<n; i++)
   {
    printf("%d \n", *(pntr+i));
   }

  free(pntr);
 }

Output



Enter number of elements:
10
1
5
3
1
6
0
15
7
56
4
Elements are:
1
5
3
1
6
0
15
7
56
4

Difference between calloc() and malloc()

The main difference between calloc() and malloc() function is that calloc() function initializes each and every byte of memory with 0 while malloc() function does not.

calloc() function takes two arguments () number of blocks and size of each block while malloc() function takes only one argument.

malloc() function reserves a block of memory of a specified number of bytes during dynamic memory allocation while calloc() function reserves a number of blocks in memory and initializes every byte with 0.

realloc() in c


realloc() function is used for changing the size of the previously allocated memory. realloc stands for re-allocation. It reallocates the size of the memory that is already being allocated in a program.

realloc function is used to resize the memory that has been already allocated in the program and that's the reason it takes only two arguments. First argument is pointer name and the second is a new size.

Syntax: 
realloc(pointer_name, new_size);
for example:
realloc(ptr1, 10*sizeof(int));     // ptr1 is previously allocated pointer name.

free() in c

free() function is used for releasing the space or free the memory that is dynamically allocated (at runtime of the program) by dynamic memory allocation in the program.

Generally, all the memories that are allocated to the program at compile time will automatically be deallocated at the end of the program.

But the dynamic memory allocation will not deallocate and as a result, there is a loss in the memory each time the program is executed. 

So, free() function is used in order to deallocate this memory which takes only one argument (previously allocated pointer name which is to be deallocated).

Syntax: 

free(pointer_name);       
for example:
free(ptr1);         //prt1 is previously defined pointer.

Example: Dynamic memory allocation in c


#include<stdio.h>
#include<stdlib.h>
int main() 
 {   
  int *pntr, n, i, temp;  
 
  printf("Enter number of elements: \n"); 
  scanf("%d", &n);

  pntr = (int *)calloc(n, sizeof(int));

  if (pntr == NULL)
   {
    printf("Allocation Failed \n");
    exit(0);
   }

  else
   {
    printf("Enter %d elements: \n", n);

    for(i=0; i<n; i++)
     {
      scanf("%d", pntr+i);
     }

    temp = *pntr;

    for(i=0; i<n; i++)
     {
      if(temp<*(pntr+i))
       {
        temp = *(pntr+i);
       }
     }
   }

  free(pntr);

  printf("Greatest number is: %d", temp);
 }

Output


Enter number of elements:
8
Enter 8 elements:
14
52
30
12
786
0
15
7
Greatest number is: 786

<< Previous                                                                                  Next >>
Previous
Next Post »

Comment Below: ConversionConversion EmoticonEmoticon