C Dynamic Memory Allocation

Releasing the used space

Compile time storage of a variable is allocated and released by the system in accordance with its storage class. With the dynamic runtime allocation, it is our responsibility to release the space when it is not required.
The release of storage space becomes important when the storage is limited. When we no longer need the data we stored in a block of memory and we do not intend to use that block for storing any other information, we may release that block of memory for future use, using the free function.
		free(ptr); 
ptr is a pointer that has been created by using malloc or calloc.

To alter the size of allocated memory

The memory allocated by using calloc or malloc might be insufficient or excess sometimes in both the situations we can change the memory size already alloc
	ptr=realloc(ptr,newsize); 
This function allocates new memory space of size newsize to the pointer variable ptr ans returns a pointer to the first byte of the memory block. The allocated new block may be or may not be at the same region.

Memory Allocation Program

/*Example program for reallocation*/<
#include< stdio.h >
#include< stdlib.h >
define NULL 0
main() 
{ 
     char *buffer; /*Allocating memory*/ 
	  if((buffer=(char *) malloc(10))==NULL) 
	   { 
       printf(“Malloc failed\n”); 
	    exit(1); 
} printf(“Buffer of size %d created \n,_msize(buffer)); strcpy(buffer,”Bangalore”); printf(“\nBuffer contains:%s\n”,buffer); /*Reallocation*/ if((buffer=(char *)realloc(buffer,15))==NULL) { printf(“Reallocation failed\n”); exit(1); } printf(“\nBuffer size modified.\n”); printf(“\nBuffer still contains: %s\n”,buffer); strcpy(buffer,”Mysore”); printf(“\nBuffer now contains:%s\n”,buffer); /*freeing memory*/ free(buffer); }

Make Comments..!!


Oops!! No posts from user.

Download Android App