>> Then strncpy() will happily 0-fill all of that buffer space
Yes. And that feels like a really poor choice of the function name in my opinion. It should have been strcpy_pad_with_zeros() rather than strncpy(). To reflect the fact that it is going to waste precious cache lines and memory writes.
It probably made sense in an era when typing was slow and fixed-length records padded with zeroes were common.
That said, if the article's code would have appeared on Stack Overflow, I wouldn't be able to prevent myself from also saying:
The author's suggested replacement, the C++ template function (!) strcpy_safe(), is not so hot in my opinion.
It uses strncpy(), which is record-oriented and thus will always fill all its n bytes. If you do:
Then strncpy() will happily 0-fill all of that buffer space, which of course is completely pointless and just a waste of precious cycles. This is because it treats the buffer as a "record", and insists to initialize all of it.This is the "flip side" of the logic that prevents it from 0-terminating if the string fills the buffer; since the buffer is a record with a known size, and not really a C string, it doesn't need to be terminated, right? Heh.
Also, POSIX reserves the namespace of functions whose names start with "str". I'm not 100% sure how well this applies to C++, but it seems prudent to avoid defining your own function with a name like that.