首页 > 解决方案 > 如何修复此 C++ UBSAN vptr 运行时错误(运行时错误:成员调用地址)

问题描述

我在我的项目中启用了 ubsan 测试 (-fsanitize=undefined) 并发现了一些 ubsan 运行时错误。谁能帮我找出这里失败的原因?如何在 GCC 和 Clang 上解决这个问题?

这是包含 lib.h 和 lib.cpp 的 lib.so 模块。

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 模块的可执行模块:

主文件

#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'

标签: c++gccclangubsan

解决方案


推荐阅读