Dynamic Memory Allocations in C

The dynamic memory allocation is a very important concept of C programming, which will give facility to allocate/de-allocate memory at run time environment.

There are four functions to maintain dynamic memory allocation at run time, which is given in below diagram.

These functions defined in stdlib.h header file of C.

Here is a C program to demonstrate the concept of malloc(), realloc() & free().

/*
 *  To demonstrate the concept of malloc(), realloc() & free()
 */
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main ( int argc, char **argv ) 
{
   char *str;
   /* Memory allocation using malloc() */
   str = ( char * ) malloc ( 16 );
   /* strcpy() copied "advancecomputing" in str */
   if ( strcpy ( str, "advancecomputing" ) == 0 )
   {
       perror ( "Copy failed\n" );
   }
   else
   {
       printf ( "String : %s,  Address : %p\n", str, str );
   }  
   /* Reallocating memory using realloc() */
   str = ( char * ) realloc ( str, 20 );
   /* strcat() concatenate the second string into first string */
   strcat ( str, ".co.in" );
   printf ( "String : %s,  Address : %p\n", str, str );
   free ( str );
   return(0);
} 

Here is a C program to demonstrate the concept of calloc() & free ().

/*
 * To demonstrate the concept of calloc () & free ()
 */
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char **argv )
{
   /* For number */
   int n = 0;
   /* For sum */
   int sum = 0;
   /* For loop processing */
   int i;
   /* integer pointer variables */
   int *ptr   = NULL;
   int *temp  = NULL;
   /* Reads input from terminal */
   printf ( "How many numbers do you want to add : " );
   scanf ( "%d", &n );
   /* Allocates memory */
   ptr = (int *) calloc ( n , sizeof (int) );
   if ( NULL == ptr )
   {
       perror( "Memory allocation failed\n" );
   }
   /* Reads the numbers from terminal */
   printf ( "Enter the %d numbers to add \n", n );
   for ( i = 0, temp = ptr ; i < n; i++, temp++)  
   {
      printf("Enter #%d: ", (i+1) );
      scanf("%d", temp);
      /* Calculates sum */
      sum += *temp;
   }
   /* Display the result */
   printf("Sum: %d\n", sum);
   /* frees the memory allocated for ptr  */
   free(ptr);
   return 0;
 } 

Hope, it would be useful !!

To contribute :

If you like Advance Computing and would like to contribute, you can mail your article to “computingadvance@gmail.com”. You will get credit like your name, email id, a designation with the article on this blog.

Leave a Reply