C: preventing buffer overflows with snprintf
A buffer overflow writes beyond the end of an array. In C it is one of the most common causes of serious security flaws, because the extra bytes can overwrite neighbouring variables or a function's return address. Functions such as gets, strcpy, and sprintf do not know the size of the destination.
C
#include <stdio.h>
static int copy_name(char *out, size_t capacity, const char *name) {
int needed = snprintf(out, capacity, "%s", name);
return needed >= 0 && (size_t)needed < capacity;
}
int main(void) {
char buffer[8];
if (copy_name(buffer, sizeof buffer, "Ada")) {
printf("stored: %s\n", buffer);
}
if (!copy_name(buffer, sizeof buffer, "Programonic")) {
printf("rejected: 11 characters do not fit in %zu bytes\n", sizeof buffer);
printf("buffer still holds: %s\n", buffer);
}
return 0;
}