Search code examples
c++getlibcurl

libcurl returns error 3: URL using bad/illegal format or missing URL when using std::string variable


I'm using libcurl and following the simple https GET tutorial from the libcurl website.

When I hardcode the website URL when setting the CURLOPT_URL option, the request works:

curl_easy_setopt(curl, CURLOPT_URL, "https://www.google.com/");
result = curl_easy_perform(curl);
if (CURLE_OK != result)
{ 
    fprintf(stderr, "HTTP REQ failed: %s\n", curl_easy_strerror(result));
}

However, when I put the URL into a std::string and then use the string as the input, it no longer works:

std::string url("https://www.google.com/");
curl_easy_setopt(curl, CURLOPT_URL, url);
result = curl_easy_perform(curl);
if (CURLE_OK != result)
{
    fprintf(stderr, "HTTP REQ failed: %s\n", curl_easy_strerror(result));
}

The request then returns with an error code of 3 (CURLE_URL_MALFORMAT) and the error says:

URL using bad/illegal format or missing URL

What am I missing here for it to work when I directly hardcode the URL but not work when I use a std::string?


Solution

  • Curl is a C library. It expects C strings (const char *) not C++ std::string objects.

    You want curl_easy_setopt(curl, CURLOPT_URL, url.c_str());