Skip to content

Checkpoint: An Owned Array

The Course
•
50 min study

A heap pointer on its own does not know how many elements it points to. Code that passes int *data around must also pass the length, and sooner or later someone passes the wrong one. The usual C solution is a small struct that keeps the pointer and its length together, plus two functions that form a pair: one that creates the storage and one that destroys it. The struct becomes the owner, and the pair of functions is the only code that allocates or frees its block.

The starter gives you the creating half, zeros_make. In this checkpoint you write the destroying half and something today's lessons only warned about: a copy of an owning struct that is truly a second owner. It is a small version of the project's Analyzer, an owning handle that must be initialized once and destroyed before it is reused.

Predict and run

Read the program before pressing Run. Write down its output and explain why the values are known.

Predict before running C
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    size_t count = 3;
    int *data = calloc(count, sizeof *data);
    if (data == NULL) { return 1; }
    printf("%d %d\n", data[0], data[2]);
    free(data);
    return 0;
}
Check your prediction
Text
0 0

calloc sets every byte to zero, and an int whose bytes are all zero is 0. Unlike malloc, reading these elements is well defined. Note that count lives in a separate variable: nothing in data remembers it.

Why copying the struct is dangerous

IntArray copy = array; copies the pointer, not the block. Now two structs each believe they own it. Destroying both is a double free, and destroying one leaves the other dangling. C will not stop you. One answer is a rule in the contract: do not copy an owning struct, pass a pointer to it instead (the project's analyzer.h says this about Analyzer). The other answer, when a caller genuinely needs an independent copy, is a function that makes one: a new block with the same values, owned by the new struct alone.

What you will use

  • A struct that owns. IntArray holds int *data and size_t length. An empty array is {NULL, 0}.
  • Validate, then commit with a local pointer, as in zeros_make.
  • Status results that say why a call failed, with *out unchanged on every failure.
  • A heap copy of bytes, as copy_topic did for a string in Owners and Borrowers.

Plan before you type

Goals, not statements.

  1. Write both contracts first. For the copy, decide what an empty source produces and what *out holds after each failure.
  2. Make array_destroy safe to call twice.
  3. Make array_copy produce an array that shares no memory with its source, and prove it with the starter's sum line.
  4. Check every line of output, then run the "Prove it can fail" steps below.

Practice

Exercise

Your turn

Write void array_destroy(IntArray *array) and Status array_copy(IntArray *out, const IntArray *source):

  • array_destroy releases the block and leaves {NULL, 0}; calling it again is harmless.
  • array_copy makes *out the owner of a new block holding the same values as *source. Changing one array afterward must not change the other. An empty source gives an empty {NULL, 0} copy and STATUS_OK. A NULL argument gives STATUS_INVALID, and running out of memory gives STATUS_NOMEM; on every failure *out is unchanged.

The starter's main must print:

Shell
copy: ok, length 3
sums: original 25, copy 65
copy of NULL: invalid, length still 3
copy of empty: ok, length 0, data NULL
after destroy: lengths 0 and 0
Your workspace C
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>

typedef enum { STATUS_OK, STATUS_INVALID, STATUS_TOO_LARGE, STATUS_NOMEM } Status;
typedef struct { int *data; size_t length; } IntArray;

const char *status_name(Status status) {
    switch (status) {
    case STATUS_OK: return "ok";
    case STATUS_INVALID: return "invalid";
    case STATUS_TOO_LARGE: return "too large";
    case STATUS_NOMEM: return "out of memory";
    }
    return "unknown";
}

/* Success: *out owns count zeroed ints. Failure: *out unchanged.
   Do not call on an array that still owns storage. */
Status zeros_make(IntArray *out, size_t count) {
    if (out == NULL || count == 0) { return STATUS_INVALID; }
    if (count > SIZE_MAX / sizeof(int)) { return STATUS_TOO_LARGE; }
    int *data = calloc(count, sizeof *data);
    if (data == NULL) { return STATUS_NOMEM; }
    out->data = data;
    out->length = count;
    return STATUS_OK;
}

long sum(const IntArray *array) {
    long total = 0;
    for (size_t i = 0; i < array->length; ++i) { total += array->data[i]; }
    return total;
}

/* Write array_destroy and array_copy here, each with its contract comment. */

int main(void) {
    IntArray original = {NULL, 0};
    if (zeros_make(&original, 3) != STATUS_OK) { return 1; }
    original.data[0] = 25;
    IntArray copy = {NULL, 0};
    Status s = array_copy(&copy, &original);
    printf("copy: %s, length %zu\n", status_name(s), copy.length);
    if (s != STATUS_OK) { return 1; }
    copy.data[1] = 40;
    printf("sums: original %ld, copy %ld\n", sum(&original), sum(&copy));
    s = array_copy(&copy, NULL);
    printf("copy of NULL: %s, length still %zu\n", status_name(s), copy.length);
    IntArray empty = {NULL, 0};
    IntArray empty_copy = {NULL, 0};
    s = array_copy(&empty_copy, &empty);
    printf("copy of empty: %s, length %zu, data %s\n", status_name(s), empty_copy.length,
        empty_copy.data == NULL ? "NULL" : "set");
    array_destroy(&copy);
    array_destroy(&original);
    array_destroy(&original);
    printf("after destroy: lengths %zu and %zu\n", original.length, copy.length);
    return 0;
}
Hint 1: the idea

Two structs may hold equal values but must never hold the same address. The copy needs its own allocation, sized from the source's length, and the values moved into it; the source pointer itself is never stored in *out.

Hint 2: a first step

Write array_destroy, and for now write array_copy as *out = *source; return STATUS_OK; after a NULL check. To see why that is wrong without crashing, also add a return 0; just after the sums line, before the destroys. Run it: the sums line says original 65, copy 65, because both structs point at one block. Without that early return the program would destroy the block twice, which may abort before anything prints. Replace the shallow assignment, remove the early return, and run until the sums line reads original 25, copy 65.

Show one solution
Run the solution C
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>

typedef enum { STATUS_OK, STATUS_INVALID, STATUS_TOO_LARGE, STATUS_NOMEM } Status;
typedef struct { int *data; size_t length; } IntArray;

const char *status_name(Status status) {
    switch (status) {
    case STATUS_OK: return "ok";
    case STATUS_INVALID: return "invalid";
    case STATUS_TOO_LARGE: return "too large";
    case STATUS_NOMEM: return "out of memory";
    }
    return "unknown";
}

/* Success: *out owns count zeroed ints. Failure: *out unchanged.
   Do not call on an array that still owns storage. */
Status zeros_make(IntArray *out, size_t count) {
    if (out == NULL || count == 0) { return STATUS_INVALID; }
    if (count > SIZE_MAX / sizeof(int)) { return STATUS_TOO_LARGE; }
    int *data = calloc(count, sizeof *data);
    if (data == NULL) { return STATUS_NOMEM; }
    out->data = data;
    out->length = count;
    return STATUS_OK;
}

long sum(const IntArray *array) {
    long total = 0;
    for (size_t i = 0; i < array->length; ++i) { total += array->data[i]; }
    return total;
}

/* Releases the storage and leaves an empty array {NULL, 0}. Safe to repeat. */
void array_destroy(IntArray *array) {
    free(array->data);
    array->data = NULL;
    array->length = 0;
}

/* Success: *out owns a new block with the same values as *source; the two
   arrays share nothing. An empty source gives an empty {NULL, 0} copy.
   Failure (NULL argument, out of memory): *out unchanged.
   Do not call on an out that still owns storage. */
Status array_copy(IntArray *out, const IntArray *source) {
    if (out == NULL || source == NULL) { return STATUS_INVALID; }
    if (source->length == 0) {
        out->data = NULL;
        out->length = 0;
        return STATUS_OK;
    }
    int *data = malloc(source->length * sizeof *data);
    if (data == NULL) { return STATUS_NOMEM; }
    memcpy(data, source->data, source->length * sizeof *data);
    out->data = data;
    out->length = source->length;
    return STATUS_OK;
}

int main(void) {
    IntArray original = {NULL, 0};
    if (zeros_make(&original, 3) != STATUS_OK) { return 1; }
    original.data[0] = 25;
    IntArray copy = {NULL, 0};
    Status s = array_copy(&copy, &original);
    printf("copy: %s, length %zu\n", status_name(s), copy.length);
    if (s != STATUS_OK) { return 1; }
    copy.data[1] = 40;
    printf("sums: original %ld, copy %ld\n", sum(&original), sum(&copy));
    s = array_copy(&copy, NULL);
    printf("copy of NULL: %s, length still %zu\n", status_name(s), copy.length);
    IntArray empty = {NULL, 0};
    IntArray empty_copy = {NULL, 0};
    s = array_copy(&empty_copy, &empty);
    printf("copy of empty: %s, length %zu, data %s\n", status_name(s), empty_copy.length,
        empty_copy.data == NULL ? "NULL" : "set");
    array_destroy(&copy);
    array_destroy(&original);
    array_destroy(&original);
    printf("after destroy: lengths %zu and %zu\n", original.length, copy.length);
    return 0;
}
Text
copy: ok, length 3
sums: original 25, copy 65
copy of NULL: invalid, length still 3
copy of empty: ok, length 0, data NULL
after destroy: lengths 0 and 0

The new block is held in a local until malloc has succeeded, so every failure returns with *out untouched. The byte count source->length * sizeof *data cannot overflow here, because the source block of exactly that size already exists. An empty source is handled before malloc, because malloc(0) may return either NULL or a unique pointer, and the contract should not depend on which. array_destroy relies on free(NULL) being a no-op, so the second call on original is safe. Tomorrow the array learns to grow, and its capacity becomes a third field.

Prove it can fail

After your solution prints the expected lines, make two deliberate changes, one at a time. First, put back Hint 2's shallow *out = *source;. The sums line becomes original 65, copy 65, and a local build with -fsanitize=address stops in array_destroy with attempting double-free: destroying copy released the block, and destroying original released it again. Second, delete the two reset lines in array_destroy: now the repeated destroy of original is the double free. Restore both changes.

Mistakes worth checking for

  • Changing the copy changes the original. The copy stores the source's pointer instead of a new block.
  • A failed copy leaves length changed. A field was assigned before the allocation succeeded. Keep the new pointer in a local until every step has succeeded.
  • Only some values are copied. The byte count passed to malloc or memcpy is the element count instead of length * sizeof *data.
  • The second destroy crashes or the sanitizer reports a double free. array_destroy frees but does not reset data to NULL. free(NULL) is safe; freeing an old pointer again is not.
  • A leak when array_copy is called on an out that already owns a block. The call overwrites that block's only owner. Destroy before copying into it again.

Was this article helpful?

Your response is saved on this device.