首页 > 解决方案 > Find causing a segmentation fault

问题描述

I have a shared library for library interposition with an unordered_map. The unordered_map is filled and consulted through the execution of an application (when intercepting specifics calls).

If I try to find an element in the constructor of the library, it generates a segmentation fault.

Here is the code for the constructor causing the segmentation fault:

void __attribute__((constructor)) init(void) { 
    void * address =  __builtin_extract_return_addr(__builtin_return_address(0));
    printf ("Size: %i\n", stats._regions.size()); // works fine
    auto regionIt = stats._regions.find(address);
    printf ("Never reached\n");
}

Stats is declared in the header, like this:

class Stats {
  public
    std::unordered_map<void *, RegionInfo> _regions;
}

As said, if I do the find when intercepting specific calls (not in the constructor), it works fine.

标签: c++segmentation-faultfind

解决方案


这是导致分段错误的构造函数的代码:

您没有显示stats全局本身是如何声明的,否则您的代码将毫无用处(另请参见MCVE)。

但这几乎可以肯定是静态初始化命令惨败的一个实例。

如何测试是否是 SIOF?如果是这种情况,请修复它

修复 SIOF 的常用方法:与其声明stats为全局变量,不如将其设为函数静态并返回对它的引用,这样可以保证在您访问它之前对其进行初始化:

Stats& get_stats()
{
  static Stats stats;
  return stats;
}

您的构造函数将如下所示:

void __attribute__((constructor)) init(void) { 
  Stats& stats = get_stats();
  // rest as before
}

如果这修复了崩溃,您就会知道它是 SIOF 的一个实例。


推荐阅读