I\'m writing a C program that should read in an essay from a user. The essay is divided into multiple paragraphs. I don\'t know how many lines or characters the essay will be,
Hmmm to "not waste space in memory",
then how about excessive calls of realloc()
?
char *Read_Paragraph_i(void) {
size_t size = 0;
size_t i = 0;
char *dest = NULL;
int ch;
while ((ch = fgetc(stdin)) != EOF) {
if (ch == '#') break;
size++;
char *new_ptr = realloc(dest, size);
assert(new_ptr);
dest = new_ptr;
dest[i++] = ch;
}
size++;
char *new_ptr = realloc(dest, size+);
assert(new_ptr);
dest = new_ptr;
dest[i++] = '\0';
return dest;
}
A more sane approach would double the allocation size every time more memory is need, temporally wasting memory and then a final "right-size" allocation.