strcpy_s(emp.s, "An example!"); // 錯誤:strcpy_s 至少需 3 參數
C11 標準 `strcpy_s` 簽名:
errno_t strcpy_s(char * restrict dest, rsize_t destsz, const char * restrict src);
**第二參數 `destsz` 為目的緩衝區大小(含結束符)**。缺少此參數導致編譯錯誤(VS 嚴格檢查)。
struct data {
char s[30];
// ...
};
struct data example() {
struct data emp;
strcpy_s(emp.s, sizeof(emp.s), "An example!"); // 正確:傳入 30
// ...
}
| 函數 | 參數順序 | 備註 |
|---|---|---|
| `strcpy_s(dest, destsz, src)` | 目的、目的大小、來源 | 取代 `strcpy` |
| `strcat_s(dest, destsz, src)` | 目的、目的大小、來源 | 取代 `strcat` |
| `sprintf_s(dest, destsz, fmt, ...)` | 目的、目的大小、格式... | 取代 `sprintf` |
| `gets_s(buf, bufsz)` | 緩衝區、大小 | 取代危險 `gets` |
`strcpy_s` 為 Microsoft 擴展後納入 C11,GCC/Clang 需 `-std=c11` 且定義 `__STDC_WANT_LIB_EXT1__` 才可用。跨平台專案建議自行封裝或用 `snprintf(dest, destsz, "%s", src)` 通用安全複製。
`strcpy_s` 報錯 = **缺少緩衝區大小參數**。修正:`strcpy_s(emp.s, sizeof(emp.s), "An example!")`。養成「安全函數必傳 size」習慣,杜絕緩衝區溢位。