4 ms·
It’s often implicitly assumed in these kind of discussions that the “safe” behavior would be to always create a truncated NUL-terminated string. That is still
by anderskaseorg 9y ago
It’s often implicitly assumed in these kind of discussions that the “safe” behavior would be to always create a truncated NUL-terminated string. That is still crazy! Do you want your data to be silently truncated?
The only safe thing to do with a string that doesn’t fit in the available space is to abort with an error. Check those return values!
For this usage, strncpy is perfectly suitable (though the performance concern may still slightly favor another approach):
if (strncpy(dst, src, size) >= size) {
abort();
}
- dllthomas 9y agoThis depends a whole lot on context. There are lots of places where silent truncation is the correct behavior. I don't disagree that return values should be checked, or that things should maybe be more explicit if you want truncation, but calling aborting "the only safe thing" is wrong.