该功能的第二个调用中的分割故障

Segmentation fault on the second call of the function?

本文关键字:分割 故障 第二个 功能 调用      更新时间:2023-10-16

edit (解决方案)

我遵循了与-fsanitize = address&的建议。Valgrind。我只使用了-fsanitize(我以前从未听说过),发现问题是什么,剩下的剩下的呼吁在另一个功能中遇到攻击函数,并且该物体被摧毁了两次。此时,内存完全危害。

也非常感谢您的帮助和其他建议。


我正在使用插座编写C 代码与CouchDB进行交谈(CouchDB是Apache的数据库,具有HTTP API)。我创建了一个整个课程来处理它,它基本上是一个连接和关闭的插座客户端。

我的功能之一是发送HTTP请求,然后阅读响应并使用它,在第一个呼叫上正常工作,但是当我第二次称呼它时失败。

但在失败的情况下它是不一致的,有时它是其中一个字符串功能中的segfault,而其他时候它是返回中的Sigabort。我已经发出了用->

崩溃的线条

最糟糕的是,它只有在"第二次"时间运行时才失败,这实际上是第10次。说明:当类实例化时,创建了一个插座,sendRequest称为8次(所有工作,总是工作),我关闭插座。然后,我有另一个控制套接字服务器的类,该类接收命令并创建执行命令的远程用户对象,然后远程用户命令调用CouchDB类以操纵DB。首次请求命令有效,但第二次失败并崩溃了程序。

额外信息:在short int httpcode行中,GDB跟踪显示了substr上的崩溃,SigaBort Crash Trace在free()上显示了一个问题。

我已经进行了很多次调试,对在何处以及如何实例化字符串和缓冲区进行了一些更改,我迷路了。有人知道为什么它会多次奏效,但随后的电话会崩溃?

CouchDB::response CouchDB::sendRequest(std::string req_method, std::string req_doc, std::string msg)
{
    std::string responseBody;
    char buffer[1024];
    // zero message buffer
    memset(buffer, 0, sizeof(buffer));
    std::ostringstream smsg;
    smsg << req_method << " /" << req_doc << " HTTP/1.1rn"
         << "Host: " << user_agent << "rn"
         << "Accept: application/jsonrn"
         << "Content-Length: " << msg.size() << "rn"
         << (msg.size() > 0 ? "Content-Type: application/jsonrn" : "")
         << "rn"
         << msg;
    /*std::cout << "========== Request ==========n"
              << smsg.str() << std::endl;*/
    if (sendData((void*)smsg.str().c_str(), smsg.str().size())) {
        perror("@CouchDB::sendRequest, Error writing to socket");
        std::cerr << "@CouchDB::sendRequest, Make sure CouchDB is running in " << user_agent << std::endl;
        return {-1, "ERROR"};
    }
    // response
    int len = recv(socketfd, buffer, sizeof(buffer), 0);
    if (len < 0) {
        perror("@CouchDB::sendRequest, Error reading socket");
        return {-1, "ERROR"};
    }
    else if (len == 0) {
        std::cerr << "@CouchDB::sendRequest, Connection closed by servern";
        return {-1, "ERROR"};
    }
    responseBody.assign(buffer);
    // HTTP code is the second thing after the protocol name and version
->  short int httpcode = std::stoi(responseBody.substr(responseBody.find(" ") + 1));
    bool chunked = responseBody.find("Transfer-Encoding: chunked") != std::string::npos;
    /*std::cout << "========= Response =========n"
              << responseBody << std::endl;*/
    // body starts after two CRLF
    responseBody = responseBody.substr(responseBody.find("rnrn") + 4);
    // chunked means that the response comes in multiple packets
    // we must keep reading the socket until the server tells us it's over, or an error happen
    if (chunked) {
        std::string chunkBody;
        unsigned long size = 1;
        while (size > 0) {
            while (responseBody.length() > 0) {
                // chunked requests start with the size of the chunk in HEX
                size = std::stoi(responseBody, 0, 16);
                // the chunk is on the next line
                size_t chunkStart = responseBody.find("rn") + 2;
                chunkBody += responseBody.substr(chunkStart, size);
                // next chunk might be in this same request, if so, there must have something after the next CRLF
                responseBody = responseBody.substr(chunkStart + size + 2);
            }
            if (size > 0) {
                len = recv(socketfd, buffer, sizeof(buffer), 0);
                if (len < 0) {
                    perror("@CouchDB::sendRequest:chunked, Error reading socket");
                    return {-1, "ERROR"};
                }
                else if (len == 0) {
                    std::cerr << "@CouchDB::sendRequest:chunked, Connection closed by servern";
                    return {-1, "ERROR"};
                }
                responseBody.assign(buffer);
            }
        }
        // move created body from chunks to responseBody
->      responseBody = chunkBody;
    }
    return {httpcode, responseBody};
}

调用上述功能,有时是sigabort

bool CouchDB::find(Database::db db_type, std::string keyValue, std::string &value)
{
    if (!createSocket()) {
        return false;
    }
    std::ostringstream doc;
    std::ostringstream json;
    doc << db_name << db_names[db_type] << "/_find";
    json << "{"selector":{" << keyValue << "},"limit":1,"use_index":"index"}";
->  CouchDB::response status = sendRequest("POST", doc.str(), json.str());
    close(socketfd);
    if (status.httpcode == 200) {
        value = status.body;
        return true;
    }
    return false;
}

您可能有一些问题:

  • CouchDB::responsestruct {httpcode: int, body: std::string}
  • CouchDB::dbenum选择不同的数据库
  • sendData仅发送任何字节,直到发送所有字节

使其 int len = recv(socketfd, buffer, sizeof(buffer), 0);可能覆盖缓冲区中的最后一个''。一个人可能很想使用sizeof(buffer) - 1,但这可能是错误的,因为您可能会在流中获得无效字节。因此,请这样做:responseBody.assign(buffer, len);。当然,只有在确保len >= 0之后进行此操作,这是您在错误检查中进行的。

您必须在每个调用recv的地方做到这一点。但是,为什么您使用recv而不是read超出了我,因为您没有使用任何标志。

另外,如果您以我的方式执行此操作,您的缓冲区memset毫无意义。您还应该在使用缓冲区之前声明您的缓冲区。我不得不阅读您的一半功能,以弄清楚您是否对此做了什么。但是,当然,您最终会第二次使用它。

heck,由于您的错误处理基本上都是相同的,因此我只能发挥一个可以做到的函数。不要重复自己。

最后,您随着find的结果快速而松动。您可能实际上找不到您要寻找的东西,而是可以将string::npos返回,这也会引起您有趣的问题。

另一件事,如果您使用的是GCC或Clang,请尝试-fsanitize=address(或在此处记录的其他Sanitize选项)。和/或在Valgrind下运行。您的内存错误可能远离崩溃的代码。这些可能会帮助您接近它。

,最后一个音符。您的逻辑完全搞砸了。您必须将阅读数据和解析分开,并为每个机器保留其他状态机。不能保证您的第一读都会获得整个HTTP标头,无论阅读多大。而且不能保证您的标题也小于一定尺寸。

您必须继续阅读,直到您阅读要么愿意为标头读并考虑到一个错误,或者直到您在标头末端获得Cr ln cr ln为止。

那些最后的位不会导致您的代码崩溃,但会导致您遇到虚假错误,尤其是在某些流量方案中,这意味着它们可能不会在测试中显示。