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
- It checks the multiplication for overflow, which malloc does not.
- The block starts as all zero bytes.
freeis the same either way.
Keywords and builtins used here
NULLforifintreturnsize_tsizeoftable_is_clean
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.
Step 2 of 5 in Dynamic memory, step 11 of 25 in Pointers & memory.