
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Why We Assume strncpy Insecure in C/C++
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
#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;