0

I'm trying to get something done quick and dirty. I saw another SO question and tried to reuse the code. I'm hitting a couple rest services (not multithreaded) that return json and when the CURLOPT_WRITEFUNCTION is called it throws a seg fault. I'm still trying to grasp all the c++ concepts so it's been pretty difficult diagnosing.

Here's what I see

static std::string *DownloadedResponse;

static size_t writer(char *data, size_t size, size_t nmemb, std::string *buffer_in)
{
    cout << "In writer callback" << endl;

    // Is there anything in the buffer?
    if (buffer_in != NULL)
    {
        cout << "Buffer not null" << endl;
        // Append the data to the buffer
        buffer_in->append(data, size * nmemb);
        cout <<" Buffer appended, seting response" << endl;

        DownloadedResponse = buffer_in;
        cout << "Set downloadedResponse" << endl;
        return size * nmemb;
    }

    return 0;
}

std::string downloadJSON(std::string URL)
{
    CURL *curl;
    CURLcode res;
    struct curl_slist *headers=NULL; // init to NULL is important
    std::ostringstream oss;
    curl_slist_append(headers, "Accept: application/json");
    curl_slist_append( headers, "Content-Type: application/json");
    curl_slist_append( headers, "charsets: utf-8");
    curl = curl_easy_init();
    if (curl)
    {
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        curl_easy_setopt(curl, CURLOPT_URL, URL.c_str());
        curl_easy_setopt(curl, CURLOPT_HTTPGET,1);
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
        curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION,writer); // I comment this to display response in stdout.

        cout << "calling easy_perform" << endl;
        res = curl_easy_perform(curl);
        cout << "call made.." << endl;
        if (CURLE_OK == res)
        {
            char *ct;
            res = curl_easy_getinfo(curl, CURLINFO_CONTENT_TYPE, &ct);
            if((CURLE_OK == res) && ct)
            {
                cout << "returning downloaded resposne" << endl;
                return *DownloadedResponse;
            }
        } 
        else 
        {
            cout << "CURLCode: " << res << endl;
        }
    }
    cout << "Returning null" << endl;
    return NULL;
}

Output

$ ./test-rest
calling easy_perform
In writer callback
Buffer not nullSegmentation fault (core dumped)

How am I improperly using the string in the writer callback function?

Community
  • 1
  • 1
Crushing
  • 487
  • 1
  • 9
  • 24

1 Answers1

0

You forgot to pass in a string pointer/reference with CURLOPT_WRITEDATA.

Daniel Stenberg
  • 54,736
  • 17
  • 146
  • 222