News for hackers. Stuff that matters.
Re:Stop using strncpy already by unwind on Thursday April 04, 2013 @03:26AM (#5491445)
It's good to see some publicity around this, my experience from Stack Overflow tells me few C programmers know about these details.

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:

    char bigbuf[1024];

    strncpy(bigbuf, "foo", sizeof bigbuf);
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.

Re:Stop using strncpy already by dchichkov on Thursday April 04, 2013 @05:08AM (#5491666)
>> 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.

Re:Stop using strncpy already by makomk on Thursday April 04, 2013 @05:41AM (#5491737)
It probably made sense in an era when typing was slow and fixed-length records padded with zeroes were common.
Re:Stop using strncpy already by dibbit on Thursday April 04, 2013 @07:37AM (#5492051)
It made sense when portability from C to C++ was important, as in now and for as long as both languages have constancy.