首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C++ mbstowcs Valgrind 報錯:緩衝區大小、釋放方式與空字元處理

     編輯:程式設計綜合問答

原始代碼問題

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;
}

關鍵修正點

  1. 緩衝區大小 (len+1)*sizeof(wchar_t),第三參數傳 len+1。
  2. 使用 malloc/free 配對,或改用 new wchar_t[len+1] 配合 unique_ptr(預設 delete[])。
  3. 確保轉換後字串以 L'\0' 結尾,wstring 構造才安全。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved