typestar

Who frees it? in C

C has no destructors, so ownership lives in the naming and the comments.

#include <stdlib.h>
#include <string.h>

/* Caller owns the result and must call name_free. */
char *name_new(const char *source) {
    size_t n = strlen(source);
    char *copy = malloc(n + 1);
    if (copy == NULL) {
        return NULL;
    }
    memcpy(copy, source, n + 1);
    return copy;
}

void name_free(char *name) {
    free(name);
}

/* Borrows only: nothing here is freed. */
size_t name_length(const char *name) {
    return strlen(name);
}

How it works

  1. A function whose name creates something returns owned memory.
  2. A matching destroy function is the other half of the contract.
  3. Borrowed pointers are const and never freed by the callee.

Keywords and builtins used here

The run, in numbers

Lines
22
Characters to type
415
Tokens
94
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 56 seconds.

Type this snippet

Step 1 of 4 in Ownership & mistakes, step 15 of 25 in Pointers & memory.

← Previous Next →