typestar

Init and destroy pairs in C

Every resource gets an init that can fail and a destroy that cannot.

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

typedef struct {
    char *name;
    int *values;
    size_t count;
} Session;

int session_init(Session *s, const char *name, size_t count) {
    memset(s, 0, sizeof *s);
    size_t n = strlen(name) + 1;
    s->name = malloc(n);
    s->values = calloc(count, sizeof(int));

    if (s->name == NULL || s->values == NULL) {
        free(s->name);
        free(s->values);
        memset(s, 0, sizeof *s);
        return 0;
    }
    memcpy(s->name, name, n);
    s->count = count;
    return 1;
}

void session_destroy(Session *s) {
    free(s->name);
    free(s->values);
    memset(s, 0, sizeof *s);
}

How it works

  1. Init returns success and leaves the object usable or empty.
  2. Destroy tolerates a partially built object.
  3. Zeroing on destroy makes a second call harmless.

Keywords and builtins used here

The run, in numbers

Lines
31
Characters to type
551
Tokens
195
Three-star pace
105 tpm

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

Type this snippet

Step 2 of 3 in Encapsulation, step 6 of 11 in APIs, errors & testing.

← Previous Next →