0

I really can not understand what my problem Here is my code:

#include <iostream>
#include <curl/curl.h>
#include <boost/regex.hpp>

using namespace std;
using namespace boost;

int Write_callback(char *data, size_t size, size_t nmemb, string *buffer)
{
  int result = 0;
  if (buffer != NULL)
  {
    buffer->append(data, size * nmemb);
    result = size * nmemb;
  }
  return result;
}

char *Get(string url)
{
    CURL *curl;
    CURLcode res;
    char *readBuffer;
    int retries = 2;

    curl = curl_easy_init();
    if (curl) {
        do {
            curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
            curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, Write_callback);
            curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);
            curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10);
            curl_easy_setopt(curl, CURLOPT_COOKIEFILE, "cookies.txt");
            curl_easy_setopt(curl, CURLOPT_COOKIEJAR, "cookies.txt");
            curl_easy_setopt(curl, CURLOPT_USERAGENT,
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.5");
            res = curl_easy_perform(curl);
        } while (CURLE_OK != res && retries--);

        curl_easy_cleanup(curl);

        return readBuffer;
    }
}

int main(int argc, char** argv)
{
    char *www = Get("google.com");

    string Str = "dsfgdasgadgasdg";
    boost::regex RegEx("(.+)");
    boost::smatch Results;
    boost::regex_match(Str, Results, RegEx);
    cout << "Print entire match:\n " << Results[1] << endl;

    return 0;
}

This compiles, but when you run an error:

terminate called after throwing an instance of 'std::length_error'
  what():  basic_string::_S_create

If I comment out this:

char *www = Get("google.com");

That works

If I comment out this:

string Str = "dsfgdasgadgasdg";
boost::regex RegEx("(.+)");
boost::smatch Results;
boost::regex_match(Str, Results, RegEx);
cout << "Print entire match:\n " << Results[1] << endl;

That works too..

Why it does not work together ??

kirill reut
  • 33
  • 1
  • 1
  • 5

1 Answers1

2

In your Get function you declare the local variable readBuffer character pointer:

char *readBuffer;

You use the address of that as the userdata for your Write_callback function. So the userdata is a char**. But in your Write_Callback you have the userdata field a a std::string:

int Write_callback(char *data, size_t size, size_t nmemb, string *buffer)

With LibCurl the callback has the userdata parameter as a void* so it isn't a std::string:

size_t write_callback(char *ptr, size_t size, size_t nmemb, void *userdata);

See http://curl.haxx.se/libcurl/c/CURLOPT_WRITEFUNCTION.html

Pass a std::string pointer as the userdata instead of a char**. And I would keep the Write_callback parameter a void* and cast that void* to a std::string* in the callback.

Hope that helps!

A.J.
  • 325
  • 1
  • 4