다음을 통해 공유


오류: new-delete-type-mismatch

삭제자 오류 해결: 할당 크기와 다른 할당 취소 크기

이 예제에서는 호출되지 않고 ~Derived,만 ~Base호출됩니다. 소멸자가 아니기 virtual때문에 컴파일러는 호출을 ~Base()Base 생성합니다. 호출 delete b할 때 개체의 소멸자가 기본 정의에 바인딩됩니다. 이 코드는 빈 기본 클래스(또는 Windows에서 1 바이트)를 삭제합니다. 소멸자 선언에서 누락된 virtual 키워드(keyword) 상속을 사용할 때 일반적인 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 오류 예제