Re: Freeing room direction

From: Mike Breuer (mbreuer@new.rr.com)
Date: 11/30/01


From: "John" <witpens@OPTUSHOME.COM.AU>
> Once I free all the strings involved in world[i].dir_option[j] (ie.
> general_description and keyword), is it ok for me to set
> world[i].dir_option[j] = NULL;

You not only can, you MUST:

/* Clear out direction "j" in room "i" */
if (world[i].dir_option[j]) {
  if (world[i].dir_option[j]->general_description)
    free(world[i].dir_option[j]->general_description);
  if (world[i].dir_option[j]->keyword)
    free(world[i].dir_option[j]->keyword);

  free(world[i].dir_option[j]);
  world[i].dir_option[j] = NULL;
}

(see below for more detail)

> It works fine if I set it to NULL but I fear I havent really cleared the
> memory (is this a memory leak here?)

Yes.  The proper procedure for freeing any pointer is:

free(ptr);
ptr = NULL;

Technically, you only have to set it to NULL if something is relying a NULL
value as an indication that it is not pointing to any allocated memory.
Since this is a very common practice, you should always set your pointers to
NULL after freeing them.  About the only time you can get away with not
doing it, is when you are freeing a pointer just before it goes out of
scope.

<ASIDE>
Since this came up in another post recently:  Don't automatically assume
that just because a variable is a pointer, that it is ok to free it.  You
are only allowed to free things that were allocated by the malloc family of
functions (which are used in Circle's CREATE/RECREATE macros).
</ASIDE>

In your specific case, there are tons of places throughout the code
(including the autoexit stuff) that use this logic:

if (world[<rnum>].dir_option[<dir>]) {
  /* Assume this is a valid exit */
}

Since the logic is somewhat obscured by the fact that it's part of the EXIT
macro, it may not be as obvious to the untrained eye.

Mike

--
   +---------------------------------------------------------------+
   | FAQ: http://qsilver.queensu.ca/~fletchra/Circle/list-faq.html |
   | Archives: http://post.queensu.ca/listserv/wwwarch/circle.html |
   +---------------------------------------------------------------+



This archive was generated by hypermail 2b30 : 12/06/01 PST