Why do we assume strncpy insecure in C/C++?

CC++Server Side Programming

The function strncpy() is used to copy the specified number of characters to the destination from the source.

The following is the syntax of strncpy()

char *strncpy( char *destination, char *source, size_t n);

Here, destination is the pointer to the destination array where the source string is to be copied, source is the string is to be copied and n is the maximum number of characters to be copied from the source string.

The strncpy() function is insecure because if the NULL character is not available in the first n characters in the source string then the destination string will not be NULL terminated.

A program that demonstrates strncpy() in C++ is given as follows.

Example

Live Demo

#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;
}

Output

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 strncpy() is used to copy the first four characters into the destination string. Then the contents of the destination string is printed. The code snippet that shows this is as follows.

char source[20] = "This is a string";
char dest[20];
strncpy(dest, source, 4);
cout << "The destination string is: " << dest;
Published on 22-Nov-2018 07:55:15