C Program for Memory Allocation and Reallocation
/*
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 large string.
*/
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *ch;
int n,n1;
printf("\n Enter Size of String you Want : ");
scanf("%d",&n);
if((ch = (char *)malloc(n *sizeof(char))) == 0)
{
printf("\n No space available");
exit(1);
}
else
{
printf("\n %ld Bytes Space are allocated Successfully", n * sizeof(char));
}
printf("\nEnter String :");
scanf("%s",ch);
printf("\n String is : %s",ch);
printf("\n Enter Size You Want Increase: ");
scanf("%d",&n1);
if((ch = (char *)realloc(ch,(n+n1) *sizeof(char))) == 0)
{
printf("\n No extra space available");
exit(1);
}
else
{
printf("\n %ld Bytes Space are allocated Successfully", (n+n1) * sizeof(char));
}
printf("\nEnter New String :");
scanf("%s",ch);
printf("\n New String is : %s",ch);
return 0;
}
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 large string.
*/
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char *ch;
int n,n1;
printf("\n Enter Size of String you Want : ");
scanf("%d",&n);
if((ch = (char *)malloc(n *sizeof(char))) == 0)
{
printf("\n No space available");
exit(1);
}
else
{
printf("\n %ld Bytes Space are allocated Successfully", n * sizeof(char));
}
printf("\nEnter String :");
scanf("%s",ch);
printf("\n String is : %s",ch);
printf("\n Enter Size You Want Increase: ");
scanf("%d",&n1);
if((ch = (char *)realloc(ch,(n+n1) *sizeof(char))) == 0)
{
printf("\n No extra space available");
exit(1);
}
else
{
printf("\n %ld Bytes Space are allocated Successfully", (n+n1) * sizeof(char));
}
printf("\nEnter New String :");
scanf("%s",ch);
printf("\n New String is : %s",ch);
return 0;
}
WELL DONE
ReplyDelete]