C/C++ strncpy 用法與範例

本篇 ShengYu 介紹 C/C++ strncpy 用法與範例,strncpy 是用來複製字串的函式,跟 strcpy 函式功能一樣是複製字串,但 strncpy 安全性更高,strncpy 詳細用法範例請繼續往下閱讀。

C 語言要複製 c-style 字串可以使用 strncpy,要使用 strncpy 的話需要引入的標頭檔 <string.h>,如果要使用 C++ 的標頭檔則是引入 <cstring>
strncpy 函式原型為

1
char * strncpy(char * destination, const char * source, size_t num);

strncpy 是將 source 字串的前 num 個字元複製到 destination。如果在複製了 num 個字元之前遇到 source 字串的結尾,則 destination 後續將填充零,直到總共複製了 num 個字元為止。
如果 source 比 num 長,destination 尾部不會加上 \0 結束字元。因此在這種情況下,destination 不應被視為以 \0 結束字元結尾的 C 字串(需注意溢出問題)。
destination 和 source 不得重疊(當重疊時請參考更安全的 memmove 替代方案)。

以下來看看 strncpy 怎麼複製字串,

cpp-strncpy.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// g++ cpp-strncpy.cpp -o a.out
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // strncpy

int main() {
char str[] = "Hello world";
char str2[64];
strncpy(str2, str, sizeof(str2)-1);
printf("%s\n", str2);

char str3[64];
strncpy(str3, "This is a string", sizeof(str3)-1);
printf("%s\n", str3);
return 0;
}

結果如下,

1
2
Hello world
This is a string

常見考題

請問下列程式有什麼問題?

1
2
3
const char* src = "abcdefghij";
char dst[10];
strcpy(dst, src);

問題在於 dst 分配了 10 大小的 char 字元陣列 char dst[10]; 總共有 10 個位置,而 src 字串實際佔 11 字元空間(包含結束字元),strcpy 時會造成 buffer overflow,意思就是 abcdefghij 這個字串 需要 11 個字元的位置才夠放,

在實務上通常會需要儘量少用 strcpy, 而改用 strncpy,strncpy 比 strcpy 多了第三個引數,第三個引數是傳入要複製幾個字元的數量,
所以我們這邊複製字串時最大長度不應超過 dst 的大小,

1
2
strncpy(dst, src, sizeof(dst)-1);
dst[sizeof(dst)-1] = '\0';

範例程式如下,

cpp-strncpy2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// g++ cpp-strncpy2.cpp -o a.out
#include <stdio.h>
#include <stdlib.h>
#include <string.h> // strncpy

int main() {
const char* src = "abcdefghij";
char dst[10];

strncpy(dst, src, sizeof(dst)-1);
dst[sizeof(dst)-1] = '\0';

printf("%s\n", dst);
return 0;
}

輸出結果如下,

1
abcdefghi

以上就是 C/C++ strncpy 的用法與範例介紹,
如果你覺得我的文章寫得不錯、對你有幫助的話記得 Facebook 按讚支持一下!

其它參考
strncpy - C++ Reference
https://www.cplusplus.com/reference/cstring/strncpy/

其它相關文章推薦
如果你想學習 C++ 相關技術,可以參考看看下面的文章,
C/C++ 新手入門教學懶人包
C/C++ strcpy 用法與範例
C/C++ strcmp 用法與範例
C/C++ strcat 用法與範例
C/C++ strstr 用法與範例
C/C++ strtok 用法與範例