c
  1. c-dynamicmemory-allocation

C Dynamic Memory Allocation

Syntax

The dynamic memory allocation in C can be done by using malloc(), calloc(), and realloc() functions.

malloc() syntax

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

calloc() syntax:

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

realloc() syntax:

ptr = realloc(ptr, newSize);

Example

#include<stdio.h>  
#include<stdlib.h> 

int main()  
{  
    int n, i, *ptr, sum = 0;  
  
    printf("Enter number of elements: ");  
    scanf("%d", &n);  
  
    ptr = (int*) malloc(n * sizeof(int));  
    
    if(ptr == NULL)                     
    {
        printf("Memory allocation failed");
        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: 3
Enter elements: 3 4 2
Sum= 9

Explanation

Dynamic Memory Allocation in C helps allocate memory at runtime from the heap section (rather than the stack where static allocation is done) using pointers. It helps conserve the use of memory, where a user is allocated memory at any time he/she needs it. Three important library functions used in the context of Dynamic Memory Allocation in C are: malloc(), calloc(), and realloc().

Use

  1. Dynamic Memory Allocation in C helps allocate new memory at runtime.
  2. Dynamic memory allocation of variables is often used where the amount of memory required can change at runtime.
  3. Dynamic allocation is used when data is too large to fit into the memory available at compile time.
  4. Dynamic memory allocation is used mainly when there is a large chunk of memory requirement.

Important Points

  • The allocated memory remains until it is freed by the program or operating system.
  • The malloc() function returns a void pointer that must be cast to an appropriate pointer type.
  • The calloc() function automatically initializes the assigned memory to 0.
  • The realloc() function is useful in case you've allocated memory using malloc or calloc and later realize that you need more memory than you've initially allocated.

Summary

Dynamic Memory Allocation in C is an important concept used in memory management applications. It helps program configure the storage required during execution when we do not know the actual size of memory required to store any variable. C uses the library functions malloc(), calloc(), and realloc() for this purpose. It is very convenient for storing data that will later be sent or received through a network or file system.

Published on: