Why replace strncpy with strlcpy
Title: Why replace strncpy with strlcpy
Author: Demon
Links: http://demon.tw/copy-paste/strlcpy-replace-strncpy.html
Copyright: All articles of this blog are subject to the terms "Attribution-NonCommercial use-share 2.5 mainland China" in the same way.
Recently looked at the module code, found that the copy of the string is used strlcpy, so we looked for the strlcpy to replace the strncpy reason.
For more information, see: http://www.gratisoft.us/todd/papers/strlcpy.html
Briefly summarize several points:
1. strcpy is the most unsafe copy of a string function because the SRC string can sometimes be very long. The strncpy function is then in order to solve the problem, but this function is somewhat tricky to implement, and it is not very good at the end of the string.
Example 1:
Char str[11];
strncpy (str, "Hello World", 11);
In Example 1, only the STR array is filled, but the string does not have a '/' Terminator.
Example 2:
Char str[20];
strncpy (str, "sample", 15);
In Example 2, 15 is far greater than the length of the string "sample", at which point the strncpy to add '/' to the rest of the section. First of all, this will affect efficiency, followed by static or calloc such an initialized array does not need to fill in ' \ '.
So when using strncpy to copy a string, this is usually the case,
Example 3:
strncpy (path, homedir, sizeof (path) –1);
Path[sizeof (path) –1] = ' \0′;
2. and strlcpy can automatically handle the problem of the end '
size_t strlcpy (char *dst, const char *SRC, size_t size);
However strlcpy is not an ANSI C function, which is generally used under Linux.
Original link: why replace strncpy with strlcpy
Why replace strncpy with strlcpy