cURL / Mailing Lists / curl-library / Single Mail

curl-library

why "mem->memory[mem->size] = 0;" in example getinmemory.c ?

From: Rieker Flaik <rieker_flaik_at_arcor.de>
Date: Sat, 18 Jun 2011 02:44:00 +0200

Hi,

I have two questions oncerning the example getinmemory.c
http://curl.haxx.se/libcurl/c/getinmemory.html

1. valgrind says that there would be a leak in:

   WriteMemoryCallback():
    mem->memory[mem->size] = 0;

  what does this line do?

2. in main():
   chunk.memory = malloc(1);

  Why do I need this malloc(1)? Why can't realloc do the rest? If I omit
this line, the program crashes.

here is a snip of the example:

static size_t
WriteMemoryCallback(void *ptr, size_t size, size_t nmemb, void *data)
{
  size_t realsize = size * nmemb;
  struct MemoryStruct *mem = (struct MemoryStruct *)data;
 
  mem->memory = realloc(mem->memory, mem->size + realsize + 1);
  if (mem->memory == NULL) {
    /* out of memory! */
    printf("not enough memory (realloc returned NULL)\n");
    exit(EXIT_FAILURE);
  }
 
  memcpy(&(mem->memory[mem->size]), ptr, realsize);
  mem->size += realsize;
  mem->memory[mem->size] = 0;
 
  return realsize;
}
 
 
int main(void)
{
  CURL *curl_handle;
 
  struct MemoryStruct chunk;
 
  chunk.memory = malloc(1); /* will be grown as needed by the realloc above */
  chunk.size = 0; /* no data at this point */
 
  curl_global_init(CURL_GLOBAL_ALL);
<SNIP>

Thanks a lot,
 rik

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