int memcmp(const void *buf1, const void *buf2, size_t count);
必須在調用前確保 count 不超過兩塊內存的實際可訪問長度。memcmp 內部不會檢查邊界,會嚴格按 count 逐字節比較,越界訪問導致未定義行為(崩潰、讀取垃圾數據、安全漏洞)。
buf1 長度 10,buf2 長度 100,傳 count=50 → 讀取 buf1 後 40 字節越界。// 安全封裝
int safe_memcmp(const void *a, size_t len_a, const void *b, size_t len_b, size_t count) {
if (count > len_a || count > len_b) {
// 記錄錯誤、返回特定錯誤碼、或截斷 count
return -2; // 自定義:長度不足
}
return memcmp(a, b, count);
}
// 或調用前斷言
assert(count <= strlen(buf1) && count <= strlen(buf2)); // 僅適用字符串
assert(count <= sizeof(buf1) && count <= sizeof(buf2)); // 僅適用定長數組
strncmp(遇 \0 停止)或 strcmp,天然受長度限制。std::string_view、std::vector、std::span(C++20)攜帶長度信息,編譯期/運行期更安全。