strncpy is not your friend
Being in IRC, every so often you will find someone heralding the use of strncpy
for writing secure code. A lot of the time they are just going off what others have said, and can’t even tell you what strncpy really does. strncpy is a problem for two reasons:
- It silently truncates data. When, in all of your experience coding, has silent truncation been acceptable behavior? Replacing one bug (a buffer overflow) with silent truncation is not a fix, it’s just hiding the problem.
- strncpy does not do what you think it does. It is not made for security—in fact, if the buffer runs out of room it will copy into the last character, not adding a null terminator! So once again, you replace a buffer overflow with another bug.
Bugs happen. Sometimes we build sanity checks into programs to combat unknown ones before they become a problem. But strncpy is not a sanity check or security feature—using it instead of resizing a buffer to accommodate the data, or just outright rejecting the data if it gets too big is a bug.
Related Posts
- Writing a good parser on January 02, 2008 in C, Coding
- Visual Studio 2008 released, TR1 support coming on November 24, 2007 in Coding
- MSDN Content Service on December 02, 2007 in Coding
- Is C# the Boost of C-family languages? on October 28, 2010 in C, Coding
- C++0x work progressing on November 28, 2007 in Coding