Strlcpy
From Wikipedia, the free encyclopedia
- The correct title of this article is strlcpy. The initial letter is shown capitalized due to technical restrictions.
The strlcpy function, developed by Todd C. Miller and Theo de Raadt for use in the C programming language, is intended to replace the function strcpy and provide a simpler and more robust interface than strncpy. It is designed to copy the contents of a string from a source string to a destination string.
size_t strlcpy(char *destination, const char *source, size_t size);
strlcpy offers two features that are designed to help software developers avoid problems. A string (of non-zero length) copied by strlcpy is always nul-terminated, making it simpler to locate the end of the string. The function takes the size of the destination as a parameter, making buffer overflows less likely. For performance reasons, strlcpy does not fill any unused space in a destination string with zeros, unlike strncpy. Additionally, strlcpy returns the length of the source string, which can be compared to size to check for truncation, for example:
if (strlcpy(dest, source, dest_len) >= dest_len) errx(1, "String too long");
strlcpy was first introduced with OpenBSD version 2.4. It has subsequently been adopted by a number of operating systems including FreeBSD (from version 3.3), Solaris and Mac OS X. Many application packages and libraries include their own copies of these functions, including glib, rsync and the Linux kernel itself.
Similarly, there is a variant of strcat, called strlcat.
[edit] Controversy
The strlcpy and strlcat functions are controversial.[1][2] It has been noted that they are non-standard, that there are implementation differences between the BSD and Solaris implementations,[3] and that no study has demonstrated that they lead to safer or more-secure software than using standard C functions.[citation needed] Furthermore, some, including Ulrich Drepper, argue that use of strlcpy and strlcat can introduce more bugs than they remove;[2] consequently, these functions have not been added to the GNU C Library. Others have expressed concern regarding the risks of truncation when using any string function involving static allocation.[4]
[edit] References
- ^ http://www.gatago.com/comp/unix/programmer/8301563.html
- ^ a b libc-alpha mailing list, selected messages from 8 August 2000 thread: 53, 60, 61
- ^ Antill, James. Security with string APIs
- ^ Antill, James. Security with string APIs: Security relevant things to look for in a string library API
[edit] External links
- strlcpy and strlcat--Consistent, Safe, String Copy and Concatenation - a paper written by Miller and de Raadt, presented at Usenix 99
- OpenBSD Manual : size-bounded string copying and concatenation –
- strlcpy() source
- strlcat() source
- Linux Weekly News discussion of strlcpy
- Developer Blog discussion of strlcpy and mempcpy