home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!mcsun!sun4nl!and!jos
- From: jos@and.nl (Jos Horsmeier)
- Newsgroups: comp.lang.c
- Subject: Re: Pointers to freed memory
- Message-ID: <3179@dozo.and.nl>
- Date: 30 Jul 92 08:20:58 GMT
- References: <1992Jul29.205834.11308@hubcap.clemson.edu>
- Organization: AND Software BV Rotterdam
- Lines: 33
-
- 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 ;-)
-
- As long as you do not dereference such a pointer (as you indicated
- yourself,) everything is fine. If pointer q contained a valid pointer
- 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
-