19

I compiled my code using -fsanitize=address and am getting this error:

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

1 Answer 1

30

C++ repeatedly gives you that feeling that you still do not understand even fundamental concepts. 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. This is because A's dtor is not virtual.

Scott Meyers says: "Polymorphic base classes should declare virtual destructors. If a class has any virtual functions, it should have a virtual destructor"

Fix this by adding

struct A {
  virtual ~A() = default;
};
2
  • 5
    What I do: declare every class that I make as final, and if I want to derive from then, I need to go to the class definition and remove the final. Then I will (hopefully :P) remember to mark the destructor as virtual.
    – Rakete1111
    Jan 9, 2017 at 17:02
  • Relevant documentation: "Deleting an object through pointer to base invokes undefined behavior unless the destructor in the base class is virtual [...] A common guideline is that a destructor for a base class must be either public and virtual or protected and nonvirtual" - en.cppreference.com/w/cpp/language/…
    – talz
    May 27, 2021 at 14:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.