Описание тега strncpy
Used to copy a maximum of n
characters of non-overlapping, fixed-width or null-terminated strings. It is defined in the <string.h>
C standard header or the <cstring>
C++ standard header.
This function is not recommended to use for any purpose, neither in C nor C++. It was never intended to be a "safe version of strcpy
" but is often misused for such purposes. It is in fact considered to be much more dangerous than strcpy
, since the null termination mechanism of strncpy
is not intuitive and therefore often misunderstood. This is because of the following behavior specified by ISO 9899:2011 7.24.2.4:
char *strncpy(char * restrict s1, const char * restrict s2, size_t n);
/--/
3 If the array pointed to by s2 is a string that is shorter than n characters, null characters are appended to the copy in the array pointed to by s1, until n characters in all have been written.
A very common mistake is to pass an s2
which is exactly as many characters as the n
parameter, in which case s1
will not get null terminated. That is: strncpy(dst, src, strlen(src));
/* MCVE of incorrect use of strncpy */
#include <string.h>
#include <stdio.h>
int main (void)
{
const char* STR = "hello";
char buf[] = "halt and catch fire";
strncpy(buf, STR, strlen(STR));
puts(buf); // prints "helloand catch fire"
return 0;
}
Recommended practice in C is to check the buffer size in advance and then use strcpy()
, alternatively memcpy()
.
Recommended practice in C++ is to use std::string
instead.
References:
- ISO/IEC 9899:2011 Information technology — Programming languages — C. Chapter 7.24.2.4.
- Why are strlcpy and strlcat considered insecure?
- /questions/15942948/kakih-funktsij-iz-standartnoj-biblioteki-sleduet-sleduet-izbegat
Documentation:
C strncpy
documentation.
C++ std::strncpy
documentation.