错误: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

生成的错误

示例 1 中显示 new-delete-type-mismatch 错误的调试程序的屏幕截图。

另请参阅

AddressSanitizer 概述
AddressSanitizer 已知问题
AddressSanitizer 生成和语言参考
AddressSanitizer 运行时参考
AddressSanitizer 阴影字节
AddressSanitizer 云或分布式测试
AddressSanitizer 调试程序集成
AddressSanitizer 错误示例