Bounded interfaces in C
Take the buffer and its capacity together, and report what was needed.
size_t format_label(char *out, size_t cap, const char *lang, int stars) {
static const char *filled = "***";
size_t needed = strlen(lang) + 1 + (size_t) stars;
if (out != NULL && cap > needed) {
size_t n = strlen(lang);
memcpy(out, lang, n);
out[n] = ' ';
memcpy(out + n + 1, filled, (size_t) stars);
out[needed] = '\0';
}
return needed;
}
How it works
- Passing a buffer without its size is how overflows happen.
- Returning the required length lets the caller retry bigger.
- This is the shape of snprintf, and it is a good shape.
Keywords and builtins used here
NULLcharconstformat_labelifintreturnsize_tstatic
The run, in numbers
- Lines
- 13
- Characters to type
- 340
- Tokens
- 112
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 67 seconds.
Step 3 of 4 in Signatures, step 3 of 11 in APIs, errors & testing.