查找导致分段错误
Find causing a segmentation fault
我有一个用于库插入的共享库 unordered_map。
unordered_map 通过应用程序的执行(在拦截特定调用时)来填充和查询。
如果我尝试在库的构造函数中查找元素,它会生成分段错误。
这是导致分段错误的构造函数的代码:
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 在 header 中声明,如下所示:
class Stats {
public
std::unordered_map<void *, RegionInfo> _regions;
}
如前所述,如果我在拦截特定调用时(不在构造函数中)执行查找,它工作正常。
Here is the code for the constructor causing the segmentation fault:
您没有说明 stats
全局变量本身是如何声明的,否则您的代码将毫无用处(另请参阅 MCVE)。
但这几乎可以肯定是静态初始化顺序失败的实例。
How can I test if is SIOF? And fix it if that's the case
修复 SIOF 的常用方法:不是将 stats
声明为全局变量,而是将其设为 function-static 和 return 对它的引用,这样可以保证它将被初始化在您访问它之前:
Stats& get_stats()
{
static Stats stats;
return stats;
}
您的构造函数将如下所示:
void __attribute__((constructor)) init(void) {
Stats& stats = get_stats();
// rest as before
}
如果这修复了崩溃,您就会知道它是 SIOF 的一个实例。
我有一个用于库插入的共享库 unordered_map。 unordered_map 通过应用程序的执行(在拦截特定调用时)来填充和查询。
如果我尝试在库的构造函数中查找元素,它会生成分段错误。
这是导致分段错误的构造函数的代码:
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 在 header 中声明,如下所示:
class Stats {
public
std::unordered_map<void *, RegionInfo> _regions;
}
如前所述,如果我在拦截特定调用时(不在构造函数中)执行查找,它工作正常。
Here is the code for the constructor causing the segmentation fault:
您没有说明 stats
全局变量本身是如何声明的,否则您的代码将毫无用处(另请参阅 MCVE)。
但这几乎可以肯定是静态初始化顺序失败的实例。
How can I test if is SIOF? And fix it if that's the case
修复 SIOF 的常用方法:不是将 stats
声明为全局变量,而是将其设为 function-static 和 return 对它的引用,这样可以保证它将被初始化在您访问它之前:
Stats& get_stats()
{
static Stats stats;
return stats;
}
您的构造函数将如下所示:
void __attribute__((constructor)) init(void) {
Stats& stats = get_stats();
// rest as before
}
如果这修复了崩溃,您就会知道它是 SIOF 的一个实例。