Please check out 4 Dimensions !

Member Discussions

terms



[Previous] [Next] [Post] [Reply] [Topics] [Summary] [Search]


1. str_dup Thu Jan 1, 2004 [7:03 AM]
leabear
Email not supplied
member since: Dec 25, 2003
Reply
Is it ok to str_dup() without freeing first? Looking
through a few codebases it has been done both
ways, in the godwars one i have it free_string() and
then str_dup() but some other derivatives don't
free_string() first, would that cause a memleak or is
it ok to str_dup without freeing first?

I hope this makes sense heh


2. RE: str_dup Thu Jan 1, 2004 [7:31 AM]
unifex
unifex@nospam_yuidesigns.net
member since: Dec 12, 2000
In Reply To
Reply
If you overwrite something that needs to be freed with strdup, then yes you need to free the string whose pointer you're overwriting first. If not, then you don't need to free anything before you strdup. (Should be applicable to str_dup as well, I think.)
Yui Unifex


3. RE: str_dup Fri Jan 2, 2004 [2:39 AM]
Genghis
Email not supplied
member since: Mar 24, 2000
In Reply To
Reply
If you do this:
    some_text = str_dup( "hi mom!" );
then you are losing control of whatever "some_text" was pointing to before. Now if that happened to have been pointing at some dynamically-allocated memory, and you now no longer have any references at all to that memory, then yes you just caused a memory leak, and you should have freed the string first.

If however it was pointing to (a) a static variable, (b) something else that will be garbage-collected later by another process you wrote (e.g. a heap manager), or (c) nothing, then you don't need to free_string() first because you haven't yet lost control of the memory that was being pointed to.

G
Keyboard missing. Think F1 to continue.




[Previous] [Next] [Post] [Reply] [Topics] [Summary] [Search]