pointers-memory · intermediate · ~15 min
Complete the alloc/use/free lifecycle in one function.
Run the full allocate-use-free lifecycle inside one function: allocate an array, use it, free it, and return a computed result with no leak.
Implement long sum_then_free(int n) that allocates an n-int array, fills it with 1, 2, ..., n, computes the total, frees the array, and returns the sum. No main — the grader calls it.
n — the number of ints (at least 1 in the tests).
Returns the sum 1 + 2 + ... + n as a long. The array is freed before returning.
sum_then_free(5) -> 15
sum_then_free(1) -> 1
free it before returning. No leaks.n — the number of ints to allocate.
The sum 1..n as a long; the array is freed before returning.
Free the array before returning; no leaks.
#include <stdlib.h>
long sum_then_free(int n) {
/* TODO */
return 0;
}
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.