Why replace strncpy with strlcpy

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.