home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!crdgw1!rdsunx.crd.ge.com!bart!volpe
- From: volpe@bart.NoSubdomain.NoDomain (Christopher R Volpe)
- Newsgroups: comp.lang.c
- Subject: Re: Pointers to freed memory
- Message-ID: <1992Jul30.180908.1013@crd.ge.com>
- Date: 30 Jul 92 18:09:08 GMT
- References: <1992Jul29.205834.11308@hubcap.clemson.edu> <3179@dozo.and.nl>
- Sender: volpe@bart (Christopher R Volpe)
- Reply-To: volpe@ausable.crd.ge.com
- Organization: GE Corporate Research & Development
- Lines: 49
- Nntp-Posting-Host: bart.crd.ge.com
-
- In article <3179@dozo.and.nl>, jos@and.nl (Jos Horsmeier) writes:
- |> In article <1992Jul29.205834.11308@hubcap.clemson.edu> mjs@hubcap.clemson.edu (M. J. Saltzman) writes:
- |> |I know that a pointer to freed memory should never be dereferenced,
- |> |but is it standard-conforming to assign or do arithmetic with such
- |> |pointers?
- |> |
- |> |The application is a routine to free the elements of a circular list.
- |> |Since I have a count of the elements, I can simply run a pair of pointers
- |> |around the list, like so:
- |> |
- |> | for ( p = head, i = 0; i < n; i++ ) {
- |> | q = p;
- |> | p = p->next;
- |> | free(q);
- |> | }
- |> |
- |> |The question comes up because on the last iteration, p->next points
- |> |to the element freed in the first iteration. Do I need to break the
- |> |circle before I start the loop? Or am I just being paranoid after the
- |> |discussion of pointers to invalid array elements?
- |>
- |> Erm, yes, I hate to say it, but you're getting paranoid ;-)
-
- I'd say that's true for most real compilers, but...
-
- |>
- |> As long as you do not dereference such a pointer (as you indicated
- |> yourself,) everything is fine. If pointer q contained a valid pointer
-
- I disagree that this will always be true. There is nothing to prevent
- an implementation from trapping assignments of invalid addresses to
- pointer variables. I wouldn't be surprised if a debugging C interpreter
- (ala Saber) did this someday.
-
- |> value _before_ the call to free(), it'll contain a valid pointer value
- |> _after_ the call. In the last iteration, the value p->next points to
- |> a location in memory where the first element of the list _would have
- |> been_ if it weren't freed in the first iteration. And, again, if you
- |> don't dereference that pointer value, everything is safe and sound.
- |>
- |> kind regards,
- |>
- |> Jos aka jos@and.nl
-
- --
- ==================
- Chris Volpe
- G.E. Corporate R&D
- volpecr@crd.ge.com
-