Everything on Standard Input

Medium

Read the whole of standard input into one heap buffer that grows to fit it, then report how much arrived and hand it back. The template already carries the parts you have met before: capacity and length are the two numbers this lesson introduced, char chunk[64] is the stack buffer fgets writes into, the loop reads until fgets returns NULL, and strcpy(text + length, chunk) appends a chunk at the end of what is already there before length moves on by chunk_length. text[0] = '\0' is there because malloc does not initialize, so the buffer has to hold an empty string before anything is appended to it. The buffer starts at a capacity of 8 bytes and every test input but one is far larger than that, so growth is not optional. What is missing is in two places. The first is TODO 1, where the template gives up on any chunk that does not fit. Grow instead: ask realloc for capacity * 2, and assign the result to a separate pointer such as grown rather than straight back to text, because realloc returning NULL frees nothing and text would then be the only pointer to a block that is still allocated, overwritten with the NULL that reported the failure. That is a leak, and fail_on_memory_leak is set on this exercise. Check grown against NULL, free text and print could not grow and return 0 if it is NULL, and otherwise set text = grown and double capacity. Make the growth a while loop rather than an if, because a 64-byte chunk arriving into an 8-byte buffer needs several doublings before it fits, and the test to keep growing is length + chunk_length + 1 > capacity, where the + 1 is the terminator this chapter opened with. The second missing piece is TODO 2: when the input was empty nothing was ever read, length is still 0, and the program must free the buffer and print no input rather than reporting zero characters. Print read followed by the character count and the word characters on its own line first, then the text exactly as it arrived, newlines and all. Free the buffer on every path out, and return 0 from every path, since a nonzero exit status fails the run however right the output looks.

Success Criteria

Your code must pass 5 test case(s) to complete this exercise. 3 hint(s) are available if you need help.

Sign in to track your progress

You can work on exercises as a guest, but sign in to track your progress and save your submissions.

This platform is built by its community

Every lesson, project, and tool on HelloC++ is funded by sponsors. Join them and help shape what we build next.

Become a Patron