← Dynamic Memory: malloc, free & the Stack vs. the Heap

Grow With Sum

hard

Read n integers into a heap array and track their sum as you go (done for you). Then grow the same allocation by one element with realloc, store the sum in that new slot, and print all n + 1 elements.

realloc(ptr, new_size) tries to resize the block ptr points to, but it is not guaranteed to resize it in place – if it needs to move the data to a bigger free region, it does that automatically and returns the new address, leaving the old pointer no longer valid to use. That’s why the standard pattern is to realloc into a different variable, check that for NULL, and only then overwrite your original pointer:

int *grown = realloc(values, new_size);
if (grown == NULL) { /* original `values` is still valid and must still be freed */ }
values = grown;

Assigning straight back into values (values = realloc(values, new_size);) is a common bug: if realloc fails and returns NULL, you’ve just overwritten your only pointer to the original block, and it leaks.

Your solution

"Run" uses the sample stdin ("3\n1 2 3"). "Submit" checks your code against all 3 test cases.

Test results

Submit your solution to run it against all test cases.

Hints

    Reference solution