typestar

calloc and zeroing in C

calloc takes a count and a size, and hands back memory already zeroed.

#include <stdlib.h>

int table_is_clean(size_t n) {
    int *table = calloc(n, sizeof(int));
    if (table == NULL) {
        return 0;
    }
    int clean = 1;
    for (size_t i = 0; i < n; i++) {
        if (table[i] != 0) {
            clean = 0;
        }
    }
    free(table);
    return clean;
}

How it works

  1. It checks the multiplication for overflow, which malloc does not.
  2. The block starts as all zero bytes.
  3. free is the same either way.

Keywords and builtins used here

The run, in numbers

Lines
16
Characters to type
234
Tokens
83
Three-star pace
95 tpm

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

Type this snippet

Step 2 of 5 in Dynamic memory, step 11 of 25 in Pointers & memory.

← Previous Next →