我在项目中启用了ubsan测试(-fsanitize = undefined),发现一些ubsan运行时错误。 谁能帮我找到它为什么失败的原因?如何在GCC和Clang上解决此问题?
这里是lib.so模块,其中包括lib.h和lib.cpp。
lib.h:
#ifndef LIB_H
#define LIB_H
#ifdef API_EXPORTS
#define API __attribute__((visibility("default")))
#else
#define API
#endif
class API Exception
{
public:
virtual ~ Exception() = 0;
void SetReporter();
};
class API FileException : public Exception
{
public:
~FileException();
};
#endif
lib.cpp:
#include "lib.h"
Exception::~Exception() = default;
FileException::~FileException() = default;
void Exception::SetReporter()
{
}
这是将调用lib.so模块的可执行模块:
main.cpp
#include "lib.h"
int main(void) {
FileException ex;
ex.SetReporter();
return 0;
}
构建模块(lib.so和main)并运行main,存在运行时错误:
build_run_gcc.sh
#!/bin/bash
# Test gcc version
gcc --version
# Build the API library
g++ -fPIC -D API_EXPORTS -o lib.so -shared lib.cpp -fvisibility=hidden -Wall -fsanitize=undefined -lubsan
# Build the main
g++ -o main main.cpp ./lib.so -fvisibility=hidden -Wall -fsanitize=undefined -lubsan
# Test main
./main
错误:
main.cpp:5:19: runtime error: member call on address 0x7ffcb88a8c60 which does not point to an object of type 'Exception'
0x7ffcb88a8c60: note: object is of type 'FileException'
14 56 00 00 48 cd 41 3d 14 56 00 00 00 fa 14 fd f4 29 3f 51 60 8d 8a b8 fc 7f 00 00 00 00 00 00
^~~~~~~~~~~~~~~~~~~~~~~
vptr for 'FileException'