Skip to content
Advertisement

I want to write a function that retrieves a webpage

I’m trying to write a function that returns the html code of a specified URL here’s my code so far:

char * getHtml()
{
    struct BufferStruct buffer;
    CURLcode result;
    CURL *myHandle;

    printf("successn");
    // Passing the function pointer to LC
    curl_easy_setopt(myHandle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
    printf("successn");
     // Passing our BufferStruct to LC
    curl_easy_setopt(myHandle, CURLOPT_WRITEDATA, (void *)&buffer);
    curl_easy_setopt(myHandle, CURLOPT_URL, "http://www.example.com");

    result = curl_easy_perform( myHandle );

    curl_easy_cleanup( myHandle );
    return buffer.buffer;
}

only the first success string is printed: success

./compile: line 3: 27548 Segmentation fault      ./a.out

here’s my writememorycallback:

static size_t WriteMemoryCallback (void *ptr, size_t size, size_t nmemb, void *data)
{
    size_t realsize = size * nmemb;        
    struct BufferStruct *mem = (struct BufferStruct *) data;

    mem->buffer = realloc(mem->buffer, mem->size + realsize + 1);   
    if (mem->buffer == NULL)
        return 0;

    if (mem->buffer)
    {
        memcpy(&(mem->buffer[ mem->size ]), ptr, realsize);
        mem->size += realsize;
        mem->buffer[ mem->size ] = 0;
    }
    return realsize;
}

the same code when embedded into the body of the main function works just fine.

Advertisement

Answer

If only the first string success is printed out then something probably went wrong with the first call to the curl function.

The first step you should do is to check every return value of curl functions:

CURLcode ok = curl_easy_setopt(myHandle, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
if( ok != CURLE_OK )
{
    printf( "Error here %dn" , __LINE__ );
}

The real reason this first call to a curl function failed is that CURL *myHandle wasn’t initialized:

So initialize it:

CURL *myHandle= curl_easy_init();
if(!myHandle) { /*handle error ...*/ }

And delete it after you are done:

curl_easy_cleanup(myHandle);

The other problem as already pointed out, is that struct BufferStruct buffer isn’t initialized, thus realloc in WriteMemoryCallback fails when called with an uninitialized pointer.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement