malloc, calloc, free and realloc in c

malloc()

malloc() function allocate a block of byte of memory in byte.

Example:

malloc( number of element * size of each element);

int * ptr;

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



Where size represents the memory required in bytes .The memory which is provided is contiguous memory.
                             
calloc()

In malloc requested memory is provided a block of contiguous memory . calloc() function  is similar to the malloc rather then calloc() function allocated the memory block for an array of elements.

Example:

void *calloc(size_t number,size_t size);

size_t used for unsigned on most compilers.The number is the number of objects which is allocate, and size is the size (in bytes) of each object.

int main () 
{      

int number,i;               

        printf("Enter the number ");     

        scanf("%d",&number); 

        printf("Number which is here are",number);      

         int *ptr = (int *) calloc (number,sizeof(int));      

        for (i=0; i<number;i++) 
       {              

                ptr[i] = i +i;

       }

       for (i=0; i<number;i++) 
       {             

               printf("Result is %d %d\n",i,ptr[i]);

       }

}

free()

For deallocation of the memory which is allocated through the malloc() function and calloc() function used free() function.

Example:

free(ptr);
 
int main () 
{

      

int number,i;

      

        printf("Enter the number ");

      

        scanf("%d",&number);

      

        printf("Number which is here are",number);

     

       for (i=0; i<number;i++) 
     {

         ptr[i] = i +i;

      }

     for (i=0; i<number;i++) 
     {
          ("Result is %d %d\n",i,ptr[i]);
      }

     free(ptr); 
}

realloc()

realloc() function is used  for resize the size of memory block which is allocated by the malloc() and calloc () function.


Two situation where use realloc() function.

    When allocated block is insufficient need more memory then use realloc().
    When allocated memory is much more then the required application then use realloc().

Example:


realloc(ptr, new size);



/* Through realloc() resize the memory . */



#include <stdio.h>

#include <stdlib.h>

#include <string.h>

  {
     char buffer[80], *msg;

   

   

     /* Input a string. */  



    puts("Enter the text line");  


     gets(buffer);

   

     /* The string copied in to initial allocated block */   
   

     msg = realloc(NULL, strlen(buffur)+1);   

       
     strcpy(msg, buffer);   

   

   

     /* Display the message which copied. */



     puts(message);

   

   

     /* Get another string from the user. */  
       
     puts("Enter another text line.");    ;

       
     gets(buffer);


     /* Resize the memory and also concatenate the string to it. */


     msg = realloc(msg,(strlen(msg) + strlen(buffer)+1));   

     strcat(msg, buffer);

     }

No comments:

Post a Comment