Re: Problem with strdup
Date: Thu, 16 Dec 2004 22:11:13 -0500
Eric VERGNAUD wrote:
>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:
>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
> char * strdup(const char *ps); // returns a copy of the string pointed to
> 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
>Since my program is written in C++, I believe strdup calls new instead of
>I believe that replacing the above line by:
> he->key = malloc(key_len);
>Will solve my problem.
>What do you think ?
>Eric VERGNAUD - JLynx Software
>Cutting-edge technologies and
>services for software companies
I think it may depend on you C++ library but in general strdup uses
malloc or at least it uses the same memory allocator that malloc does.
Also, I believe that if the C++ library had a different implementation
of strdup then it would be likely that it would also provide a different
implementation of free that obeyed the C++ memory allocator rules. What
i'm saying is I don't think this is the answer to your problem...
Received on 2004-12-17