Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

ทำไม strncpy ถือว่าไม่ปลอดภัยใน C/C++


ฟังก์ชัน strncpy() ใช้ copy จำนวน characters ที่ระบุจาก source ไป destination

Syntax ของ strncpy():

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

destination คือ pointer ไป destination array source คือ string ที่จะ copy n คือ max number of characters ที่ copy จาก source

strncpy() ไม่ปลอดภัยเพราะถ้า NULL character ไม่อยู่ใน n characters แรกของ source string destination string จะไม่ NULL terminated

โปรแกรมสาธิต 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 output of the above program is as follows.

The destination string is: This

เข้าใจโปรแกรมข้างต้น:

Source string มีข้อมูล "This is a string" strncpy() copy 4 ตัวอักษรแรกไป destination string แล้วพิมพ์ destination string Code snippet:

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