\0 結尾,長度 = strlen,sizeof 包含結尾符;char 有符號性由編譯器決定,跨平台建議顯式使用 signed/unsigned char 或 std::string。// 危險 char buf[8]; gets(buf); // 已棄用,C11 移除 strcpy(buf, argv[0]); // 無長度檢查 // 安全 char *buf = malloc(strlen(src)+1); if (buf) strcpy(buf, src); // 或 C++ 推薦 std::string s = src;
strncpy 不保證以 \0 結尾,需手動補齊;snprintf 返回值可能超過緩衝區大小,需檢查。棧溢出可覆蓋返回地址,注入 Shellcode。防禦:
-fstack-protector-strong -D_FORTIFY_SOURCE=2;std::string / std::vector 自動管理內存。std::string 陷阱// 迭代器失效示例
std::string email;
auto it = email.begin();
for (char c : input) {
if (c == ';') it = email.insert(it, ' '); // 必須用返回值更新
else it = email.insert(it, c);
++it;
}
// GB2312 → UTF-8 int wlen = MultiByteToWideChar(CP_ACP, 0, gbkStr, -1, nullptr, 0); wchar_t* wstr = new wchar_t[wlen]; MultiByteToWideChar(CP_ACP, 0, gbkStr, -1, wstr, wlen); int ulen = WideCharToMultiByte(CP_UTF8, 0, wstr, wlen, nullptr, 0, nullptr, nullptr); char* utf8 = new char[ulen]; WideCharToMultiByte(CP_UTF8, 0, wstr, wlen, utf8, ulen, nullptr, nullptr); utf8[ulen-1] = '\0'; // 使用完畢 delete[] wstr; delete[] utf8;
Linux 下可用 iconv 庫實現相同功能。