分段故障(核心转储)-不知道为什么

Segmentation fault (core dumped) - dont know why

本文关键字:不知道 为什么 转储 故障 核心 分段      更新时间:2023-10-16

我正在学习C++的路上。我正在尝试在运行时链接库。我得到一个分段错误。我不知道为什么会这样。以下是发生错误的cpp文件:

#include "CreateShape.h"
#include <dlfcn.h>
#include <iostream>
#include <sstream>
#include "Shape.h"
namespace six
{
typedef six::Shape* (*GET_OBJECT);
Shape* create_shape(const char* name)
{
Shape* shape = nullptr;
std::stringstream libName;
libName << "./lib" << name << ".so";
void* handle = dlopen(libName.str().c_str(), RTLD_LAZY);
if(handle == nullptr)
{
std::cout << "Could not open the library" << std::endl;
std::cout << "dlerror: "<< std::endl << dlerror() << std::endl;
exit(EXIT_FAILURE);
}
GET_OBJECT createShape = reinterpret_cast<GET_OBJECT>(dlsym(handle, "getNewShape"));
if(createShape == nullptr)
{
std::cout << "Could not find symbol getNewShape" << std::endl;
std::cout << "dlerror=" << dlerror() << std::endl;
dlclose(handle);
exit(EXIT_FAILURE);
}
return create_shape(name);
}
}

功能的精简版本是

Shape* create_shape(const char* name)
{
if(some_condition)
{
exit(EXIT_FAILURE);
}
if(some_other_condition)
{
exit(EXIT_FAILURE);
}
return create_shape(name);
}

您可能想要返回shape或在该函数中创建的某些Shape。相反,您所做的是递归地调用函数。停止递归的唯一方法是满足其中一个条件,然后调用exit

不过,我不得不承认,为什么这种症状是一个我真的不明白的错误。

您没有以正确的方式使用dl调用。从linux dlopen(3(手册页

dlsym((

[…]由于符号的值实际上可能是NULL(因此dlsym()的NULL返回不需要指示错误(,测试错误的正确方法是调用dlerror()以清除任何旧的错误条件,然后调用dlsym(),然后再次调用dlerror(),将其返回值保存到变量中,并检查保存的值是否不是NULL。

相关文章: