c++ - 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.
解决方案
这是导致分段错误的构造函数的代码:
您没有显示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 的一个实例。
推荐阅读
- angular - 响应式表单上的输入数组
- visual-studio-code - FreeBSD 是否有任何 VS 代码扩展?
- flutter - Flutter PagedListView 在渲染时不保留动态小部件
- python - 在 pandas 中,如何创建一个将 0 或 1 值捕获为字符串列表的新列?
- docker - Google Cloud 上的 Docker 容器卷绑定
- docker - 如何在 docker 中配置 ksqldb BASIC 身份验证
- python - 过滤网络中的节点,重新着色未选择的节点
- terraform - 是否存在通过不同环境(从开发到生产)推广 Terraform .tfplan 文件的可接受的工作流程方案?
- linux - 为什么汇编中的可执行文件有很大的尺寸?
- lua - LUA 脚本在编译时产生错误