strcat(char *_Destination, const char *_Source) 用於將源字符串追加到目標字符串末尾,返回目標字符串指針。但它是 C 語言中最常見的安全隱患來源之一。
若連接後的字符串長度超過目標數組定義的大小,將導致內存越界覆蓋相鄰數據,引發不可預測的崩潰或安全漏洞。
void charWrite() {
FILE *file;
char type[4] = "wt+";
char path[30] = "C:/Users/Fahy/Desktop/"; // 已佔用 22 字節
char filename[20];
scanf("%s", filename); // 若輸入超過 8 字符,strcat 將導致 path 越界
strcat(path, filename);
// ... 後續文件操作
}
path 總長 30,初始佔 22,剩餘 8 字節(含結束符 \0)。若用戶輸入超過 7 個字符的文件名,strcat 寫入時將越界。
char path[256]),但無法從根本杜絕風險。strncat 限制長度:strncat(dest, src, sizeof(dest) - strlen(dest) - 1) 確保不超出邊界。strcat_s,Windows 有 StringCchCat,Linux 可用 asprintf 動態分配。malloc/realloc 分配足夠空間,用完 free 釋放。strcat/strcpy/sprintf 等非安全函數調用。-fstack-protector-strong、MSVC 的 /GS)。safeclib)替換標準庫危險函數。