[comp.os.msdos.programmer] free

resnicks@netcom.UUCP (Steve Resnick) (01/23/91)

In article <8822@star.cs.vu.nl> tamboer@cs.vu.nl (Tamboer Erik) writes:
>A question about the free() function in C. I'm posting it here because I
>thought I might reach a few C programmers here ;-)
>
>Is it safe to free() a block of memory that has already been free()d?
>I have a program that malloc()s trees of structs that may or may not be
>free()d at some later point. Upon termination, it is important that they
>are all released from memory. Is it safe to just free all trees, including
>those that have already been freed, or do I have to resort to something
>like changing every occurence of free() in the program by { free(tree);
>tree = NULL } ? (as free(NULL) is supposed to be harmless).
>
>This is to be a portable program, so it must work with most implementations
>of free(), compiler-independent.

This is a frequently asked question in comp.lang.c, and really belongs there.

No, it's not adviseable to free a block of memory which hasn't been
malloced. If it's been free()'d, then it's not longer malloced.


Hope this helps...
Steve

-- 
-------------------------------------------------------------------------------
resnicks@netcom.com, stever@octopus.com, steve.resnick@f105.n143.z1.FIDONET.ORG
apple!camphq!105!steve.resnick, {apple|pyramid|vsi1}!octopus!stever
- In real life: Steve Resnick. Flames, grammar and spelling errors >/dev/null
0x2b |~ 0x2b, THAT is the question.
-------------------------------------------------------------------------------

tamboer@cs.vu.nl (Tamboer Erik) (01/23/91)

Well, it seems it is not safe to free() already freed memory. I thought
maybe the system would keep track of its malloc()ed space and would
know if the block one tries to free() is already free. Wishful thinking.
Well, I came up with a routine that did in fact crash my system when trying
to free already freed memory (recursively!) so I'm convinced. I have found
a satisfactory solution for my particular problem, so I'll live.

Thanks to Raymond Chen and Jamshid Afshar (my docs really say nothing
about freeing memory twice!)
and to Steve Resnick, who pointed out that I should have posted my
question to comp.lang.c. Sorry, I didn't even know that group exists!

Erik
--
    ____________________       ________________________________________
   / Erik Tamboer      /\__   / I would have included a really funny  /\__
  / tamboer@cs.vu.nl  /__\/  / joke here, but I already logged out.  /__\/
 /___________________/      /_______________________________________/

bright@nazgul.UUCP (Walter Bright) (01/27/91)

In article <8822@star.cs.vu.nl> tamboer@cs.vu.nl (Tamboer Erik) writes:
/Is it safe to free() a block of memory that has already been free()d?

No. On many implementations, this will cause your program to crash.