網頁

2011年1月8日 星期六

strncpy & strcpy

strcpy

strcpy knows the end when seeing a \0, if there is no enough space pointed by "to", then buffer overflow will happen. The following is an example of strcpy (from OpenBSD 3.9)


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

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

But sometimes "from" points to a very long string, so strcpy is not save.

strncpy

In ANSI C, strncpy is the save version of strcpy.

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

But strncpy behaves strangely. It doesn't guarantee to put a \0 at the end.

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

In the above code, buf will be filled by "abcdefgh" with no \0 at the end.
On the contrary, if the contents of "s2" is shorter than "n", strncpy will fill all remaining space by \0, and thus the performance will be lower.
char buf[80];
strncpy( buf, "abcdefgh", 79 );

The above code will fill 79 chars instead of only "abcdefgh".

Therefore, the standard usage of strncpy is like following(write a '\0' by yourself):

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

沒有留言:

張貼留言