gpt4 book ai didi

c++ - basic_string 析构函数中的段错误

转载 作者:行者123 更新时间:2023-11-28 00:25:56 26 4
gpt4 key购买 nike

我有一个函数,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::request 函数中返回任何 std::string 对象,但它被声明为具有 std::string 返回类型。我现在的问题是:为什么要编译?这是我用来编译它的命令行,使用 g++ 4.8.2:

g++ -Iinclude -std=c++11 -g -D__DEBUG -c src/HTTP.cpp -o obj/HTTP.o

没有发出警告或错误。

最佳答案

问题是我声明了 HTTPConn::request() 函数,返回类型为 std::string,但没有返回任何内容。正如 Frédéric Hamidi 所说,这会导致未定义的行为。

在我看来,这应该是 g++ 默认启用的警告,因为它会导致未定义的行为。或者它应该是一个错误。将 -Wall 标志添加到编译命令会启用此警告(或 -Wreturn-type 以仅启用该特定警告)

关于c++ - basic_string 析构函数中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25113962/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com