pointers-memory · intermediate · ~12 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 (zero and negative counts are rejected).

Output

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.

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.

Why this matters

Drill: practice one contract before combining it with other skills.

Input format

n — the number of ints (zero and negative counts are rejected).

Output format

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.

Constraints

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.

Starter code

#include <stdlib.h>

long sum_then_free(int n) {
    /* TODO */
    return 0;
}

Common mistakes

Returning before free, using a formula that skips the allocation exercise, or reading after cleanup.

Edge cases to handle

n=1; moderate large n; invalid counts; forced failure; every successful allocation is freed once.

Up next

Solve this exercise in the browser editor — compile and run against the test harness, no setup required.