Program 66) Write a program to store a character string in a block of memory space created by malloc and then modify the same to store a larger string.
The output illustrates that the original buffer size obtained is modified to contain a larger string. Note that the original contents of the buffer remains same even after modification of the original size.
PROGRAM
#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, "HYDRABAD") ;
printf ("\nBuffer contains: %s \n ", buffer) ;
/* Realloction */
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, "SECUNDERABAD") ;
printf ("\nBuffer now contains: %s \n", buffer) ;
/* Freeing memory */
free (buffer) ;
}
Output: Buffer of size 10 created
Buffer contains: HYDERABAD
Buffer size modified
Buffer still contains: HYDRABAD
Buffer now contains: SECUNDERABAD
No comments:
Post a Comment