Solution for Exercise 20-7
ex2007
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *input;
int len;
input = (char *)malloc(sizeof(char)*1024);
if(input==NULL)
{
puts("Unable to allocate buffer! Oh no!");
exit(1);
}
puts("Type something long and boring:");
fgets(input,1023,stdin);
len = strlen(input);
if(realloc(input,sizeof(char)*(len+1))==NULL)
{
puts("Unable to reallocate buffer!");
exit(1);
}
puts("Memory reallocated.");
puts("You wrote:");
printf("\"%s\"\n",input);
return(0);
}
Notes
* In the book, I give the impression that the realloc() function returns either the original pointer or a NULL pointer. It can return either one, but it can also return a new address for the buffer. That happens if the current address cannot be reallocated to the proper quantity.
Copyright © 1997-2025 by QPBC.
All rights reserved
