pointers-memory · intermediate · ~15 min

Allocate, use, free

Complete the alloc/use/free lifecycle in one function.

Challenge

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.

Task

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.

Input

n — the number of ints (at least 1 in the tests).

Output

Returns the sum 1 + 2 + ... + n as a long. The array is freed before returning.

Example

sum_then_free(5)   ->   15
sum_then_free(1)   ->   1

Rules

  • Compute the sum while the array is still alive, then free it before returning. No leaks.

Input format

n — the number of ints to allocate.

Output format

The sum 1..n as a long; the array is freed before returning.

Constraints

Free the array before returning; no leaks.

Starter code

#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.