cURL / Mailing Lists / curl-library / Single Mail

curl-library

CURLOPT_WRITEFUNCTION - cannot make it working...

From: Paolo Piacentini <paolopiace_at_hotmail.com>
Date: Fri, 3 Jun 2011 20:58:26 -0700

It happens that I need to use the CURLOPT_WRITEFUNCTION and I'm stuck...

In the main() I do this:

        curl_easy_setopt(sessionA, CURLOPT_WRITEFUNCTION, writeFunction);
        curl_easy_setopt(sessionA, CURLOPT_WRITEDATA, (void *)&storedUndrl);

        // Here I check and verify that storedUndrl is properly initialized: POSITIVE!

        curl_easy_setopt(sessionA, CURLOPT_URL, UndrlURL.c_str());
        result = curl_easy_perform(sessionA);

The downloaded page should get stored here (global scope):

struct thread_status {
        char *data;
        size_t currentSize;
        size_t spacemade;
} storedUndrl = {NULL, 0, 0};

Here is the writeFunction. Things go awry immediately at the very 1st call, where I added comments.

Does someone have any idea about what's going wrong or what I'm doing wrong?

Thanks!!

size_t static writeFunction( void *ptr, size_t size, size_t nmemb, void *thePage)
{
        size_t NEWSPACE = 400000;
        size_t nbytes = size*nmemb;

        struct thread_status *page_status = (struct thread_status *)thePage;

        // At the first call (*page_status).currentSize and (*page_status).spacemade
        // should both be equal 0, as initialized. Instead they both are huge size_t numbers.

        // The increment immediatley here below works: the huge currentSize gets incremented
        // by the corret amount.

        (*page_status).currentSize += nbytes;

        if ( (*page_status).currentSize > (*page_status).spacemade ) {
                (*page_status).data = (char *)realloc( (*page_status).data, (*page_status).spacemade );

                // Segmentation fault occurs here because (*page_status).spacemade is huge! ~3G!

                (*page_status).spacemade += NEWSPACE;
        }

        // realloc: in case ptr==NULL (1st argument), the function behaves as malloc, allocating a block
        // of size given by the 2nd argument (in bytes) and returning a pointer to the beginning of it.

        assert((*page_status).data != NULL);
        memcpy((*page_status).data + (*page_status).currentSize +1, ptr, nbytes);

        return nbytes;
}

                                               

-------------------------------------------------------------------
List admin: http://cool.haxx.se/list/listinfo/curl-library
Etiquette: http://curl.haxx.se/mail/etiquette.html
Received on 2011-06-04