原始代碼問題
wchar_t *ws2 = (wchar_t*)malloc(len * sizeof(wchar_t));
mbstowcs(ws2, s1, 100); // 第三參數應為 len,非固定 100
unique_ptr wstr(ws2); // unique_ptr 預設用 delete[],但 malloc 需 free
return wstring(ws2); // ws2 未以 L'\0' 結尾,wstring 構造會越界讀取
Valgrind 錯誤對應
- Invalid write/read:
mbstowcs 寫入超出 len*sizeof(wchar_t) 緩衝區(第三參數 100 過大)。
- Mismatched free:
malloc 配對 free,不可用 delete[](unique_ptr 預設行為)。
- Invalid read in wcslen:
wstring 構造尋找結尾空字元,讀取越界。
修正版本
wstring w2chs3(const char* s1) {
size_t len = strlen(s1);
// 配置 len+1 確保有空間存放結尾 L'\0'
wchar_t* ws2 = (wchar_t*)malloc((len + 1) * sizeof(wchar_t));
if (!ws2) throw bad_alloc();
size_t converted = mbstowcs(ws2, s1, len + 1);
if (converted == (size_t)-1) { free(ws2); throw runtime_error("轉換失敗"); }
wstring result(ws2); // 正確以 L'\0' 結尾
free(ws2);
return result;
}
關鍵修正點
- 緩衝區大小
(len+1)*sizeof(wchar_t),第三參數傳 len+1。
- 使用
malloc/free 配對,或改用 new wchar_t[len+1] 配合 unique_ptr(預設 delete[])。
- 確保轉換後字串以
L'\0' 結尾,wstring 構造才安全。