为什么我们在 C/C++ 中认为 strncpy 不安全?


函数 strncpy() 用于将指定的字符数从源地址复制到目标地址。

以下是 strncpy() 的语法

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

此处,destination 为目标数组的指针(源字符串将复制到该数组中),source 为要复制的字符串,n 为从源字符串复制的字符的最大数。

函数 strncpy() 不安全,因为如果在源字符串的前 n 个字符中没有空字符,则目标字符串将不会以空字符结尾。

如下所示,给出了一个展示 C++ 中 strncpy() 的程序。

示例

 在线演示

#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

现在让我们来理解以上程序。

源字符串包含数据“This is a string”。然后使用 strncpy() 将前四个字符复制到目标字符串中。然后打印目标字符串的内容。显示此操作的代码段如下所示。

char source[20] = "This is a string";
char dest[20];
strncpy(dest, source, 4);
cout << "The destination string is: " << dest;

更新于: 2020-06-26

501 浏览量

开启您的 职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.