Solution for Exercise 20-8
ex2008
#include <stdio.h> #include <stdlib.h> #include <string.h> int main() { char *input; int len; /* allocate storage */ input = (char *)malloc(sizeof(char)*1024); if(input==NULL) { puts("Unable to allocate buffer! Oh no!"); exit(1); } /* gather input */ puts("Type something long and boring:"); fgets(input,1023,stdin); /* resize the buffer */ len = strlen(input); input = realloc(input,sizeof(char)*(len+1)); if( input==NULL ) { puts("Unable to reallocate buffer!"); exit(1); } puts("Memory reallocated."); /* output results */ puts("You wrote:"); printf("%s",input); return(0); }
Output
Type something long and boring:
Is this long enough and boring enough for you?
Memory reallocated.
You wrote:
Is this long enough and boring enough for you?
Notes
* The input
buffer is resized and any excess storage is released for use again.
* This method of reallocation is often how programs efficiently manage storage. After all, storing a short string of text in a 1K buffer is a waste of space. Here you see how the storage can be modified so that only what's necessary is used.
* The realloc() function can both increase and decrease a buffer's size. Specify the new buffer size as the second argument, and you're good to go.
Copyright © 1997-2024 by QPBC.
All rights reserved