c++ - 从 ASAN 获取新的删除类型不匹配

标签 c++ address-sanitizer

我使用 -fsanitize=address 编译了我的代码,但出现了这个错误:

==53702==ERROR: AddressSanitizer: new-delete-type-mismatch on 0x60300000efe0 in thread T0:
  object passed to delete has wrong type:
  size of the allocated type:   24 bytes;
  size of the deallocated type: 1 bytes.
    #0 0x7fd544b7b0a0 in operator delete(void*, unsigned long) /home/user/objdir/../gcc-6.3.0/libsanitizer/asan/asan_new_delete.cc:108
    #1 0x4010c4 in foo() /home/user/asan.cpp:27
    #2 0x40117e in main /home/user/asan.cpp:33
    #3 0x7fd543e7082f in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x2082f)
    #4 0x400f48 in _start (/home/user/a.out+0x400f48)

示例代码:

#include <memory>

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

struct A {};

struct B : public A {
  T t;
};

int main() {
  A *a = new B;
  delete a;

  std::unique_ptr<A> a1 = std::make_unique<B>();

  return 0;
}

最佳答案

C++ 反复让您感觉您仍然不了解基本概念。在这种情况下:继承。

通过向 ctors 和 dtor 添加 print 语句,您会发现对于两个指针(旧式指针和智能指针),仅调用 ~A,而不调用 ~B。这是因为 A 的 dtor 不是虚拟的。

Scott Meyers 说:“多态基类应该声明虚析构函数。如果一个类有任何虚函数,它应该有一个虚析构函数”

通过添加来解决这个问题

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

关于c++ - 从 ASAN 获取新的删除类型不匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41552966/

相关文章:

c++ - 使用 getline 函数读取文件,但第一列显示为空

android - 如何设置 llvm-symbolizer?

c++ - std::vector 手动中毒

gcc - 地址 sanitizer (-fsanitize=address) 与 tcmalloc 一起使用?

c - 了解作用域后堆栈使用错误

c++ - 使用类成员作为成员函数的默认参数

c++ - 使用 boost::serialization 将派生类指针序列化为 vector 的问题

c++ - 内联函数 - 它们与 inline 关键字相比究竟是什么?

c++ - 为什么不 boost 元组运算符 == 和 << 编译?