basic_string析构函数中的段错误
segfault in basic_string destructor
我有一个函数ModuleManager::tick()
,代码如下:
void ModuleManager::tick()
{
auto now = std::chrono::steady_clock::now();
auto nowSys = std::chrono::system_clock::now().time_since_epoch();
for(auto& m : m_modules)
{
if(std::chrono::duration_cast<std::chrono::seconds>(now - m.second) >=
std::chrono::seconds(m.first.m_settings.m_interval))
{
std::string result = m.first.run(); //run() returns a std::string
m.second = now;
try
{
HTTPConn conn("127.0.0.1", 80);
conn.request("POST", "/", std::vector<std::string>{"Host: localhost", "Connection: close"}, result);
}
catch(HTTPException& e)
{
Log::write(e.getErrorString());
}
}
}
程序在从HTTPConn::request()
函数返回时,在basic_string析构函数中出现分段错误(已经使用GDB确定了这一点)。如果我注释掉request()函数中的所有代码,仍然会出现段错误,所以问题一定在该函数之外。
我相信问题是,在我的HTTPConn
构造器的某个地方,我破坏了堆。代码如下:
HTTPConn::HTTPConn(const std::string& host, int port)
{
addrinfo hints;
addrinfo* res;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
int result = getaddrinfo(host.c_str(), std::to_string(port).c_str(), &hints, &res);
if(result)
{
throw HTTPException(HTTPE_GETADDRINFO_FAILED);
}
addrinfo* ptr = res;
bool validSocket = false;
while(ptr)
{
m_socket = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol);
if(m_socket == -1)
{
ptr = ptr->ai_next;
}
else
{
validSocket = true;
break;
}
}
if(!validSocket)
{
freeaddrinfo(res);
throw HTTPException(HTTPE_SOCKET_FAILED);
}
result = connect(m_socket, ptr->ai_addr, ptr->ai_addrlen);
freeaddrinfo(res);
if(result == -1)
{
close(m_socket);
m_socket = -1;
if(errno == ECONNREFUSED)
{
throw HTTPException(HTTPE_CONNECTION_REFUSED);
}
else if(errno == ENETUNREACH)
{
throw HTTPException(HTTPE_NETWORK_UNREACHABLE);
}
else if(errno == ETIMEDOUT)
{
throw HTTPException(HTTPE_TIMED_OUT);
}
else
{
throw HTTPException(HTTPE_CONNECT_FAILED);
}
}
}
我为大量的代码道歉;我试图做一个简短的、独立的例子,但无法重现这个问题。
<标题> 更新所以问题似乎是我没有在HTTPConn::请求函数中返回任何std::string
对象,但它被声明为具有std::string
返回类型。我现在的问题是:为什么这是编译?这是我用来编译它的命令行,使用g++ 4.8.2:
g++ -Iinclude -std=c++11 -g -D__DEBUG -c src/HTTP.cpp -o obj/HTTP.o
没有警告或错误。
标题>问题是我用返回类型std::string
声明了HTTPConn::request()
函数,但是没有返回任何东西。正如fracry Hamidi所说,这会导致未定义的行为。
在我看来,这应该是一个在g++中默认启用的警告,因为它会导致未定义的行为。或者这应该是一个错误。将-Wall
标志添加到编译命令中会启用此警告(或者-Wreturn-type
只启用特定的警告)
相关文章:
- 为什么PyImport_ImportModule python 3.7.2 中出现段错误?
- 为什么在访问 vtkRenderWindow 的"交互器"变量时会发生段错误?
- 全局向量导致 C++ 程序结束时出现段错误
- 为什么重载运算符<<打印特征类成员会导致段错误?
- 更改条件段错误
- 使用 TTF_RenderText() 加载字体时获取段错误 TTF_OpenFontRW()
- 注册对对象工厂的调用会导致段错误
- pthread_create在构造函数段错误中
- Nanoflann发现邻居提出段错误
- C++ 中的构造函数、继承、堆栈、堆、this-pointer 和段错误
- 具有unique_ptr的 CRTP 会导致段错误
- 增强纤维work_stealing屏障会导致段错误
- 当我返回指向结构的指针向量时出现段错误
- C++为什么我的代码没有爆炸/段错误?
- Pthread段错误,使用指向main中变量的指针
- C++ 模板中的段错误
- 相当于Windows/MSVC上的段错误?
- 为什么我的 LLVM JIT 实现出现段错误?
- 为什么访问我的引用捕获变量会导致我的 lambda 函数出现段错误?
- 为什么自删除的全局 Vulkan 实例仅在添加层时才导致段错误?