pointers-memory · intermediate · ~12 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 (zero and negative counts are rejected).
On success returns the sum 1 + 2 + ... + n as a long; invalid sizes, an unrepresentable sum, or allocation failure return -1. The array is freed before returning.
sum_then_free(5) -> 15
sum_then_free(1) -> 1
free it before returning. No leaks.Drill: practice one contract before combining it with other skills.
n — the number of ints (zero and negative counts are rejected).
On success returns the sum 1 + 2 + ... + n as a long; invalid sizes, an unrepresentable sum, or allocation failure return -1. The array is freed before returning.
For n <= 0, allocation-size overflow, sum overflow, or allocation failure return -1. Otherwise allocate and fill 1..n, sum into long, free the array, and return the sum. No ownership escapes.
#include <stdlib.h>
long sum_then_free(int n) {
/* TODO */
return 0;
}
Returning before free, using a formula that skips the allocation exercise, or reading after cleanup.
n=1; moderate large n; invalid counts; forced failure; every successful allocation is freed once.
Solve this exercise in the browser editor — compile and run against the test harness, no setup required.