cURL / Mailing Lists / curl-library / Single Mail

curl-library

How do I free the memory used by an in-memory, non-formdata post request? (HeapValidate exception)

From: Ola Mork <ola_at_agoragames.com>
Date: Mon, 11 Oct 2010 14:09:46 -0400

Hello -

I'm working with building requests with CURLOPT_READDATA. My setopts
look like this:

_request.size = body_buffer.tellp();
_request.memory = (char *)REALLOC(_request.memory, _request.size + 1);

_request.memory = body_buffer.str();
curl_easy_setopt(_hnd, CURLOPT_POST, 1);
curl_easy_setopt(_hnd, CURLOPT_READDATA, (void *)&_request);
curl_easy_setopt(_hnd, CURLOPT_READFUNCTION, ReadMemoryCallback);
curl_easy_setopt(_hnd, CURLOPT_POSTFIELDSIZE, _request.size);

My _request definition looks like this:

struct MemoryStruct {
  char *memory;
  size_t size;
};

And my readdata callback looks like this:

size_t Client::ReadMemoryCallback( void *ptr, size_t size, size_t
nmemb, void *data) {
  struct MemoryStruct *mem = (struct MemoryStruct *)data;

  if(size*nmemb < 1)
    return 0;

  if(mem->size) {
    *(char *)ptr = mem->memory[0];
    mem->memory++;
    mem->size--;
    return 1;
  }

  return 0;
}

I've reviewed this example: http://curl.haxx.se/libcurl/c/post-callback.html

The critical difference is that I'm heap allocating my
MemoryStruct.memory instead of stack allocating it like the example
does.

Everything functions as expected. My problem is that after I've called
curl_easy_perform the address of my _request.memory changes and I can
no longer safely free it. I get a HeapValidate exception because
libcurl changes the address to somewhere in not-my-memory-space.

What is the correct way to free _request.memory? Is it already free'd
by curl and I don't need to worry about it? I'd rather not call
curl_global_cleanup after every single request.

I discovered this using libcurl 7.16.4 but it's apparent in 7.21.1 too.

-- 
Ola Mork
Senior Software Engineer
Agora Games
359 Broadway
Troy, NY 12180
ola_at_agoragames.com
Phone: 518.268.1000
www.agoragames.com
-------------------------------------------------------------------
List admin: http://cool.haxx.se/list/listinfo/curl-library
Etiquette:  http://curl.haxx.se/mail/etiquette.html
Received on 2010-10-11