strcpy, strncpy, strlcpy (reprint)

A lot of people already know that the use of alternative strcpy strncpy to prevent cross-border buffer zone.
But if you also consider the operational efficiency, perhaps strlcpy is a better way.


1. strcpy

We know, strcpy is based on \ 0 as the end of the judgment, if it is not enough to space, will cause buffer overflow. strcpy conventional codes are as follows (from OpenBSD 3.9):

char *
strcpy(char *to, const char *from)
{
       char *save = to;

       for (; (*to = *from) != ''; ++from, ++to);
       return(save);
}

But in general, are derived from our user's input is likely to be a very large string, so strcpy not safe enough.


2. strncpy

In ANSI C, the secure version is strcpy strncpy.

char *strncpy(char *s1, const char *s2, size_t n);

Strncpy but their behavior is very strange (not in line with our usual habits). Standard number n is not the char sizeof (s1), but to copy. One of the most common problem is that strncpy does not guarantee the end to help you.

char buf[8];
strncpy( buf, "abcdefgh", 8 );

Look at this program, buf will be "abcdefgh" fill, but not a terminator.

Further, if the content is less s2 and n and relatively large, then, will be the space between strncpy are filled. It appeared a matter of efficiency, as follows:

char buf[80];
strncpy( buf, "abcdefgh", 79 );

The above strncpy will fill 79 char, rather than just "abcdefgh" itself.


strncpy Standard usage is hand-written on :()

strncpy(path, src, sizeof(path) - 1);
path[sizeof(path) - 1] = '';
len = strlen(path);


3. strlcpy

// Copy src to string dst of size siz. At most siz-1 characters
// will be copied. Always NUL terminates (unless siz == 0).
// Returns strlen(src); if retval >= siz, truncation occurred.
size_t
strlcpy(char *dst, const char *src, size_t siz);

The use strlcpy, we do not need to go hand in charge of \ 0, and just make sizeof (dst) strlcpy to announce:

strlcpy(path, src, sizeof(path));
len = strlen(path);

if ( len >= sizeof(path) )
       printf("src is truncated.");

And strlcpy returned is strlen (str), so we can easily determine whether the data is truncated.

 

[* A little history *]

strlcpy not part of ANSI C, so far not a standard.

strlcpy from OpenBSD 2.4, after many libc unix-like systems have joined the strlcpy function in FreeBSD, Linux which are found strlcpy. (Linux using glibc, glibc there strlcpy, then all Linux versions should have strlcpy)

But under Windows is no strlcpy, the corresponding function is strcpy_s

Reproduced in: https: //www.cnblogs.com/shelvenn/archive/2008/02/15/1069656.html

Guess you like

Origin blog.csdn.net/weixin_33711641/article/details/93272930