Dynamic Memory Allocation in C

Dynamic Memory Allocation in C | There are 4 library functions defined under for dynamic memory allocation in C programming.

  • malloc() :- Allocates requested size of bytes and returns a pointer first byte of allocated space.
  • calloc() :- Allocates space for an array element, initializes to zero and then returns a pointer to memory.
  • free() :- Deallocate the previously allocated space.
  • realloc() :- Change the size of previously allocated space.

Malloc() used to allocate memory to structures (user-defined data types).
On successful allocation, it returns the base address of memory block. On failure, it returns the NULL pointer.

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

struct student
{
     int id;
     char name[20];
     float fee;
};
struct student *ptr;

int main()
{
     ptr=(struct student*) malloc(sizeof(struct student));

     /*check memory is allocated or not*/
     if(ptr==NULL)
         {
             printf("Memory not allocated\n");
             exit(1);
         }

     else
         {
             printf("Enter Student details (Student Id, Name & fee):\n");
             scanf("%d,%s,%f",&ptr->id,ptr->name,&ptr->fee);

             printf("\n\nStudent details is:\n");
             printf("%d,%s,%.2f",ptr->id,ptr->name,ptr->fee);
         }

     return 0;
}

Output:-

Enter Student details (Student Id, Name & fee):
1204,amelia,1205.2
Student details is:
1204,amelia,1205.02

Calloc() allocates memory to arrays. On success, it allocates ( n * size ) bytes and returns base address. On failure, it returns the NULL pointer.

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

int main()
{

     int n, i, *arr;

     printf("Enter size of array: ");
     scanf("%d",&n);

     /*allocate memory using calloc()*/
     arr= (int*) calloc(n, sizeof(int));

     /*check memory is allocated or not*/
     if(arr==NULL)
     {   
         printf("Memory not allocated.");
         exit(0);
     }

     else
     {
         printf("Array elements are:\n");
         for(i=0; i<n; i++)
         {
             printf("%d\t",*(arr+i));
         }
     }

     return 0;
 }

Output:-

Enter size of array: 3
Array elements are:
0 0 0

Notice:- when we initialize memory dynamically with calloc() than all elements of array initialize with “0“.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or you find anything incorrect? Let us know in the comments. Thank you!

Some Examples C programming

Leave a Comment

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