The Longest Line, Kept

Medium

Read lines until the input runs out and report the longest one. The template already carries the machinery you have met before: char line[64] is the buffer, while (fgets(line, sizeof(line), stdin) != NULL) reads until fgets returns NULL, the newline is stripped with the guarded test from last lesson, and the two printf calls at the bottom are written for you and must not be changed. What is missing is this lesson's whole subject, and it is in three places. The first is make_copy, which the template stubs out with return NULL. Ask malloc for strlen(source) + 1 bytes, the characters plus the terminator that nobody counts, check the result against NULL and return NULL when the allocation failed, then copy with strcpy and return the block. The + 1 is the exercise. Leave it out and the terminator lands one byte past the end of the block, which is a heap-buffer-overflow with a WRITE, and the run ends there. There is no cast on the malloc and no length check above the strcpy, and the missing check is deliberate rather than an oversight: the destination was sized from this very source one line earlier, so strlen(source) < strlen(source) + 1 could never be false. The second missing piece is the comparison. longest is NULL until something has been kept, and that first line always wins; after that, a line is kept only when strlen(line) is strictly greater than strlen(longest), so a later line of equal length changes nothing and the earlier one is reported. The third is the replacement, and it is what fail_on_memory_leak is watching. When a longer line arrives you allocate a new copy and overwrite longest with it, and the block longest used to point at is then unreachable and unfreeable, which is chapter 4's first leak shape. Free before you overwrite. No special case is needed for the first line, because longest is NULL there and free(NULL) is a defined no-op. Free the kept block on every way out too, including the allocation-failure path the template already writes and the final printf path, and note the reason the copy is needed at all: line is one buffer that fgets writes over on every iteration, so a pointer saved into it would follow the buffer rather than hold the text. When no line was ever read, print no input and nothing else. main returns 0 on every path, since the checker treats a nonzero exit status as a failure however correct the printed 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