錯誤: new-delete-type-mismatch

位址清理程式錯誤:解除配置大小與配置大小不同

在此範例中,只會 ~Base 呼叫 、 和 而非 ~Derived 。 編譯器會產生 對 的呼叫 ~Base()Base 因為解構函式不是 virtual 。 當我們呼叫 delete b 時,物件的解構函式會系結至預設定義。 程式碼會刪除空白基類 (或 Windows 上的 1 個位元組)。 解構函式宣告上的遺漏 virtual 關鍵字是使用繼承時常見的 C++ 錯誤。

範例 - 虛擬解構函式

// example1.cpp
// new-delete-type-mismatch error
#include <memory>
#include <vector>

struct T {
    T() : v(100) {}
    std::vector<int> v;
};

struct Base {};

struct Derived : public Base {
    T t;
};

int main() {
    Base *b = new Derived;

    delete b;  // Boom! 

    std::unique_ptr<Base> b1 = std::make_unique<Derived>();

    return 0;
}

多型基類應該宣告 virtual 解構函式。 如果類別具有任何虛擬函式,它應該具有虛擬解構函式。

若要修正範例,請新增:

struct Base {
  virtual ~Base() = default;
}

若要建置及測試此範例,請在 Visual Studio 2019 16.9 版或更新版本的 開發人員命令提示字元 中執行下列命令:

cl example1.cpp /fsanitize=address /Zi
devenv /debugexe example1.exe

產生的錯誤

Screenshot of debugger displaying new-delete-type-mismatch error in example 1.

另請參閱

AddressSanitizer 概觀
AddressSanitizer 已知問題
AddressSanitizer 組建和語言參考
AddressSanitizer 執行時間參考
AddressSanitizer 陰影位元組
AddressSanitizer 雲端或分散式測試
AddressSanitizer 偵錯工具整合
AddressSanitizer 錯誤範例