3 ms·
strncpy() isn't dangerous. People have their heads so twisted around muh security that they don't even know what the function was intended to do. The purpose of
by jart 5y ago
strncpy() isn't dangerous. People have their heads so twisted around muh security that they don't even know what the function was intended to do. The purpose of strncpy() is to prepare a static search buffer so you can do things like perform binary search:
static const struct People {
char name[8];
int age;
} kPeople[] = {
{"alice", 29}, //
{"bob", 42}, //
};
int GetAge(const char *name) {
char k[8];
int m, l, r;
l = 0;
r = ARRAYLEN(kPeople) - 1;
strncpy(k, s, 8);
while (l <= r) {
m = (l + r) >> 1;
if (READ64BE(kPeople[m].s) < READ64BE(k)) {
l = m + 1;
} else if (READ64BE(kPeople[m].s) > READ64BE(k)) {
r = m - 1;
} else {
return kPeople[m].age;
}
}
return -1;
}
It was a really common practice back in the 70's and 80's when the function was designed for databases to use string fields of a specific fixed length.
- jancsika 5y ago> strncpy() isn't dangerous Suppose the C specification said that string constants are automatically null terminated unless they are a certain size that is platform-dependent. At that given size the null is not added. (And let's say above that size there's a compiler error. Let's also say there's a pragma for telling the compiler you want a bigger limit on the maximum string constant size.) Would that behavior be dangerous in your opinion?