RE: cURL bug -- Segmentation Fault when timeout is 1 second
Date: Wed, 4 Feb 2009 10:39:24 -0800
Please don't top-post. http://curl.haxx.se/mail/etiquette.html
Daniel Marschall on February 04, 2009 10:24 AM wrote:
> I am very confused at the moment. Can you please help me? I don't know
> to do. It doesn't work...
> Now I have again a memory-access-error :-(
> static int writer(char* data, size_t size, size_t nmemb, char* buffer)
> // What we will return
> int result = 0;
> // Is there anything in the buffer?
> if (buffer != NULL)
> buffer = (char*)realloc(buffer, size * nmemb); // Extend
> the buffer
No, this does not "extend" the buffer. It will resize the buffer to
exactly size*nmemb bytes (and forget how large it was before). Did
you read the documentation for realloc()?
> // Append the data to the buffer
> strcat(buffer, data);
You claimed that you didn't use "strncpy() or a similar function".
certainly qualifies. This is dangerous code, causing potential buffer
overruns and security risks. Did you earlier say this code runs on a
root server? That would be scary. Again, use memcpy() or a similar
For example, assume "buffer" is infinitely large (for now), and
is the next element in "buffer" that you will write to. More correct
code would be:
memcpy( &buffer[lastindex], data, size*nmemb );
lastindex += size*nmemb;
Of course, in reality you would need to ensure that buffer is large
to hold the new data. At a minimum, your realloc call would be:
buffer = realloc( buffer, lastindex + 1 + size*nmemb );
But this is inefficient, because you would call realloc on every write
callback. It is better to allocate a large buffer, and then expand it
in large chunks as needed later on.
GaryM at Casabi
Received on 2009-02-04