為什麼我們在 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.