简体   繁体   English

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

[英]Getting new-delete-type-mismatch from ASAN

I compiled my code using -fsanitize=address and am getting this error: 我使用-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)

Example Code: 示例代码:

#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++ repeatedly gives you that feeling that you still do not understand even fundamental concepts. C ++反复给你一种感觉,你甚至不理解基本概念。 In this case: Inheritance. 在这种情况下:继承。

By adding print statements to the ctors and dtors, you will find that for both pointers (old style and smart pointer) only ~A, not ~B is called. 通过向ctors和dtors添加print语句,你会发现对于两个指针(旧式和智能指针)只有~A,而不是~B被调用。 This is because A's dtor is not virtual. 这是因为A的dtor不是虚拟的。

Scott Meyers says: " Polymorphic base classes should declare virtual destructors. If a class has any virtual functions, it should have a virtual destructor" Scott Meyers说:“ 多态基类应该声明虚拟析构函数。如果一个类有任何虚函数,它应该有一个虚拟析构函数”

Fix this by adding 通过添加修复此问题

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM