Two Blocks, Every Path Out
MediumThis exercise is unusual, and the difference is the whole point: the program you are given already prints the right answer on every test case, and it fails all of them anyway. It reads a positive count, allocates two blocks of that many ints, values and doubled, reads the numbers into values, sets doubled[i] to twice values[i], and prints two lines, sum: followed by the total of the numbers and doubled sum: followed by the total of the doubled ones. All of that is written for you and none of it is wrong. What is missing is the free calls, so every run allocates two blocks and returns without giving either of them back, and because this exercise sets fail_on_memory_leak a leaked block fails the run even when the output matches byte for byte and the exit status is zero. Three TODOs mark the frees, and there are three of them rather than one because there are three ways out of this program and each one owns a different set of blocks. TODO 3 is the easy one, the success path at the bottom, where both blocks are live. TODO 2 is the one people forget: if scanf converts nothing part way through the fill, the program reports expected followed by the count and the word numbers and returns, and at that moment both blocks are just as live as they are on the success path, so both have to go. TODO 1 is the subtle one, the path taken when the second malloc returns NULL, where values already exists and doubled does not, so exactly one block is yours to release; the graders cannot make an allocation fail, so that branch is there to be correct rather than to be exercised, which is precisely the kind of error path that leaks in real programs. Free the blocks in the reverse of the order they were taken, doubled before values, which costs nothing here and is the habit that stays right when one block depends on another. The count guard at the top is already written and handles zero, a negative count, and input that is not a number at all, each printing expected a positive count and returning before anything is allocated, which is why that path has nothing to free. Every path returns 0. Write exactly one free per allocation on every route through the program: free a block twice and AddressSanitizer reports attempting double-free, and read one after freeing it and it reports heap-use-after-free.
Success Criteria
Your code must pass 7 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.