首页 > 解决方案 > Linux中的Libcurl c ++分段错误(核心转储)

问题描述

我编写了一个代码,在 Windows(VS 2017)中运行良好。但现在我尝试将其转换为 Linux。第一个请求成功完成,但第二个请求引发分段错误。

这是我的写回调函数。(我认为这是一个问题)

size_t callback(
        const char* in,
        size_t size,
        size_t num,
        string* out)
    {
        const size_t totalBytes(size * num);
        out->clear();
        out->append(in, totalBytes);

        return totalBytes;
    }

这是我的发送消息功能。

CURL* initMessageSend(string* auth_token) {
    CURL *hnd = curl_easy_init();

    string token = "Authorization: bearer " + *auth_token;

    curl_easy_setopt(hnd, CURLOPT_CUSTOMREQUEST, "POST");
    curl_easy_setopt(hnd, CURLOPT_URL, "https://oauth.reddit.com/api/compose");

    struct curl_slist *headers = NULL;
    headers = curl_slist_append(headers, "cache-control: no-cache");
    headers = curl_slist_append(headers, "User-Agent: cpp/c");
    headers = curl_slist_append(headers, "Content-Type: application/x-www-form-urlencoded");
    headers = curl_slist_append(headers, token.c_str());
    curl_easy_setopt(hnd, CURLOPT_HTTPHEADER, headers);

    curl_easy_setopt(hnd, CURLOPT_WRITEFUNCTION, callback);

    return hnd;
}

void sendMessage(string* auth_token, string username,string subject) {

    CURL* hnd = initMessageSend(auth_token);
while (1) {
        char ch = getch();

        if (ch == 's') {
            string msg = "";
            cout << "\n\nEnter Message:";

            getline(cin, msg);

            msg = "to=" + username + "&text=" + msg + "&subject=" + subject;
            curl_easy_setopt(hnd, CURLOPT_POSTFIELDS, msg.c_str());

            CURLcode ret = curl_easy_perform(hnd);

            if (ret == CURLE_OK) {
                cout << "(sent)";
            }
        }
    }
}

获取令牌的第一个请求是成功的,但是在发送消息时它给了我分段错误。

标签: c++libcurl

解决方案


推荐阅读