The function strncpy() is used to copy the specified number of characters from the source to the destination.
The following is the syntax of strncpy()
char *strncpy( char *destination, char *source, size_t n);
Here, destination is a pointer to the destination array into which the source string will be copied, source is the string to be copied, n is the maximum number of characters to copy from the source string.
The strncpy() function is unsafe because if there are no NULL characters in the first n characters of the source string, the target string will not be NULL-terminated.
The following is a program that demonstrates the strncpy() function in C.
Online demonstration
#include <iostream> #include <cstring> using namespace std; int main () { char source[20] = "This is a string"; char dest[20]; strncpy(dest, source, 4); cout << "The destination string is: " << dest; return 0; }
The output of the above program is as follows.
The destination string is: This
Now let us understand the above program.
The source string contains the data "This is a string". Then use strncpy() to copy the first four characters into the target string. Then print the contents of the target string. A code snippet showing this is below.
char source[20] = "This is a string"; char dest[20]; strncpy(dest, source, 4); cout << "The destination string is: " << dest;
The above is the detailed content of Why do we think strncpy in C/C++ is unsafe?. For more information, please follow other related articles on the PHP Chinese website!