为什么我们在C / C ++中假定strncpy不安全?
该功能strncpy()用于将指定数量的字符从源复制到目标。
以下是语法strncpy()
char *strncpy( char *destination, char *source, size_t n);
在这里,destination是指向要复制源字符串的目标数组的指针,source是要复制的字符串,n是要从源字符串复制的最大字符数。
该strncpy()函数不安全,因为如果源字符串的前n个字符中没有NULL字符,则目标字符串将不会以NULL终止。
strncpy()给出了用C++演示的程序,如下所示。
示例
#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 destination string is: This
现在让我们了解上面的程序。
源字符串包含数据“这是一个字符串”。然后strncpy()用于将前四个字符复制到目标字符串中。然后打印目标字符串的内容。显示此代码段如下。
char source[20] = "This is a string"; char dest[20]; strncpy(dest, source, 4); cout << "The destination string is: " << dest;
热门推荐
3 祝福语简短的微信
10 幼儿祝福语大全简短贺卡
11 感谢教官文案祝福语简短
12 鼠年同事祝福语简短创意
13 元旦祝福语 简短独特群发
14 妈咪跟我生日祝福语简短
15 给儿子新婚祝福语简短
16 伴娘祝福语长文案简短
17 恭喜高考完祝福语简短
18 生日祝福语送老公简短