C++ Program to illustrate memory allocation with malloc, calloc and realloc [DEVCPP/GCC]

MALLOC

It requests a block of memory from the heap. If the request is granted, a block of required size is allocated and a pointer to the beginning of block is returned. The content of allocated block is not initialized with any default value i.e. It contains garbage value upon allocation.
ptr=(type*)malloc(size) 
CALLOC

It allocates contiguous blocks of requested size for an array and initializes all of its bits to 0. The effective result of calloc is the allocation of (No of Blocks * Size of each Block) bytes.
ptr=(type*)calloc(n,size)
REALLOC

It changes the size of previously allocated memory object pointed by given pointer and reallocates it with given size. The contents of memory object remains unchanged upto the minimum of old and new sizes. If the current memory object cannot be enlarged to satisfy the request, the function may move the memory block to a new location. The old memory object is then freed. If no memory object can be acquired to accommodate the request, the object remains unchanged.
ptr=realloc(ptr,newsize)
FREE

A block of memory previously allocated by a call to malloc, calloc or realloc is deallocated making it available again for further allocations.
free(ptr)
PROGRAM

//Program to illustrate memory allocation with malloc, calloc and realloc with their initialization and   deallocation

#include <iostream>
#include <stdlib.h>

using namespace std;

int main()
{
       int i,n,r,*cal,*mal;

       cout<<"\nENTER NUMBER OF VALUES REQUIRED: ";
       cin>>n;

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

       cout<<"\nMALLOC INITIAL ADDRESS:"<<mal;
   
       cout<<"\n\nMALLOC INITIAL MEMORY CONTENTS\n";
       for(i=0;i<n;i++)
       {
            cout<<"M["<<i<<"]: "<<mal[i]<<endl;
       }

       free(mal);

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

        cout<<"\nCALLOC INITIAL ADDRESS:"<<cal;
        cout<<"\n\nCALLOC INITIAL MEMORY CONTENTS\n";

        for(i=0;i<n;i++)
        {
              cout<<"C["<<i<<"]: "<<cal[i]<<endl;
        }

  cout<<"\nALTER NUMBER OF VALUES REQUIRED: ";
  cin>>r;

  realloc(cal,r*sizeof(int));

  cout<<"\n\nCALLOC MEMORY CONTENTS AFTER REALLOCATION\n";
  for(i=0;i<r;i++)
        {
              cout<<"C["<<i<<"]: "<<cal[i]<<endl;
        }
     
        free(cal);
        return 0;
}

OUTPUT

C++ Program to illustrate memory allocation with malloc, calloc and realloc with output


Share this

Related Posts

FIND US ON FACEBOOK!