cURL / Mailing Lists / curl-users / Single Mail

curl-users

Problem with strdup

From: Eric VERGNAUD <eric.vergnaud_at_jlynx.com>
Date: Fri, 17 Dec 2004 04:01:06 +0100

Hi,

I hope I'm wrong but I think I've identified a potential memory problem in
libcurl, that has been annoying me for some time now.

I'm compiling libcurl using gcc on MacOS X. Then I'm linking libcurl.a in my
app compiled with CodeWarrior 9.

I noticed that each time I call curl_easy_cleanup, MallocDebug complains
about libcurl freeing an unallocated block.

Today I decided to track this down, whch is not easy because I cannot debug
libcurl.a from CodeWarrior.

I had a look at the block for which MallocDebug complains, and it showed
the host address I just called, that is 127.0.0.1:8080.

Then using atos I decoded the stack trace and found the following:
_curl_easy_cleanup
_Curl_hash_destroy
_Curl_hash_clean
_Curl_llist_destroy
_Curl_llist_remove
__hash_element_dtor
_free
_unlockedfree
_printStack

Which shows that __hash_element_dtor calls free on an unallocated block.

I discovered that the only element added through Curl_hash_add is entry_id
in cache_resolv_response . entry_id is created by create_hostcache_id. Looks
like the problematic entry.

I had a look at Curl_hash_add and mk_hash_element and found the following:

    he->key = strdup(key);

On the web, I read the following:

The general rule is simple. C++ uses new and delete for dynamic memory
allocation, whereas C uses malloc and free.

 Memory allocated with new should be deallocated with delete only.

 Memory allocated with malloc should be deallocated with free only.

 Mixing them produces undefined results. Do not mix them! Unfortunately,
its not always easy to obey this simple rule. Consider the string duplicate
function:
   char * strdup(const char *ps); // returns a copy of the string pointed to
by ps

   char * newName = strdup (oldName);
        ...
   // finished with newName, deallocate it

 How will you deallocate newName? If the strdup() you're using is from a C
library you must use free, but if it's from a C++ library you must use
delete. What you must do varies from system to system and compiler to
compiler. To avoid such problems try not to use functions that are neither
in the standard library, nor available in a stable form on most computing
platforms.

Since my program is written in C++, I believe strdup calls new instead of
malloc.

I believe that replacing the above line by:

    he->key = malloc(key_len);
    memcpy(he->key,key,key_len);

Will solve my problem.

What do you think ?

-------------------------------
Eric VERGNAUD - JLynx Software
Cutting-edge technologies and
services for software companies
web: http://www.jlynx.com
-------------------------------
Received on 2004-12-17