LWN.net Logo

The ups and downs of strlcpy()

The ups and downs of strlcpy()

Posted Jul 20, 2012 0:16 UTC (Fri) by ewen (subscriber, #4772)
Parent article: The ups and downs of strlcpy()

Apparently not mentioned in the article is that strncpy() and friends will not only NUL terminate the string (so long as there is room) they will also NUL fill the entire rest of the buffer, doing much more work than is likely to be required if the destination is big. strlcpy() and friends just add the one NUL to make a valid string. So perfomance wise you can safely use it in place of strcat() all the time.

IMHO (and that of the *BSD folks), strlcpy() is the least bad trade off of performance and reliability of all the variations. It's most unfortunate that "just use strlen()" and other slow suggestions keep coming up as a viable alternative -- if performance is that little a concern that you can scan the source string twice, you might as well just use a language with managed strings anyway.

This seems to be a "perfect is the enemy of the good" situation, in a problem space where there is no "safe, fast, easy -- pick any three" solution.

Ewen


(Log in to post comments)

Copyright © 2013, Eklektix, Inc.
Comments and public postings are copyrighted by their creators.
Linux is a registered trademark of Linus Torvalds