cURL / Mailing Lists / curl-library / Single Mail

curl-library

[EXAMPLE] Bug in getinmemory.c

From: Martin Mller <moeller.akt_at_googlemail.com>
Date: Tue, 10 May 2011 19:42:52 +0200

Hello @ all,

I found a bug in getinmemory.c in docs/examples.
This version misuses realloc: It resizes a chunk of memory, but doesnt take
into
account that the realloced memory address changes.

I think this file was never actually tested.

Attached is a patch for solving the problem
(The diff is stored in unified form):

--- getinmemory.c.orig 2011-05-10 19:23:37.000000000 +0200
+++ getinmemory.c 2011-05-10 19:30:10.000000000 +0200
@@ -39,19 +39,24 @@
 WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data)
 {
   size_t realsize = size * nmemb;
+ char * reall;
   struct MemoryStruct *mem = (struct MemoryStruct *)data;
 
- mem->memory = realloc(mem->memory, mem->size + realsize + 1);
- if (mem->memory == NULL) {
+ reall = malloc(mem->size + realsize + 1);
+ if (reall == NULL) {
     /* out of memory! */
- printf("not enough memory (realloc returned NULL)\n");
+ printf("not enough memory (malloc returned NULL)\n");
     exit(EXIT_FAILURE);
   }
 
- memcpy(&(mem->memory[mem->size]), ptr, realsize);
+ if (mem->memory)
+ memcpy (reall, mem->memory, mem->size);
+
+ memcpy(reall + mem->size, ptr, realsize);
   mem->size += realsize;
- mem->memory[mem->size] = 0;
+ reall [mem->size] = 0;
 
+ mem->memory = reall;
   return realsize;
 }
 
@@ -62,7 +67,7 @@
 
   struct MemoryStruct chunk;
 
- chunk.memory = malloc(1); /* will be grown as needed by the realloc
above */
+ chunk.memory = NULL; /* will be grown as needed by the malloc above */
   chunk.size = 0; /* no data at this point */
 
   curl_global_init(CURL_GLOBAL_ALL);
@@ -71,7 +76,7 @@
   curl_handle = curl_easy_init();
 
   /* specify URL to get */
- curl_easy_setopt(curl_handle, CURLOPT_URL, "http://www.example.com/");
+ curl_easy_setopt(curl_handle, CURLOPT_URL, "http://www.google.de/");
 
   /* send all data to this function */
   curl_easy_setopt(curl_handle, CURLOPT_WRITEFUNCTION,
WriteMemoryCallback);

------
Best regards,
Martin Moeller

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