home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #16 / NN_1992_16.iso / spool / comp / lang / c / 11746 < prev    next >
Encoding:
Internet Message Format  |  1992-07-30  |  1.6 KB

  1. Path: sparky!uunet!mcsun!sun4nl!and!jos
  2. From: jos@and.nl (Jos Horsmeier)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: Pointers to freed memory
  5. Message-ID: <3179@dozo.and.nl>
  6. Date: 30 Jul 92 08:20:58 GMT
  7. References: <1992Jul29.205834.11308@hubcap.clemson.edu>
  8. Organization: AND Software BV Rotterdam
  9. Lines: 33
  10.  
  11. In article <1992Jul29.205834.11308@hubcap.clemson.edu> mjs@hubcap.clemson.edu (M. J. Saltzman) writes:
  12. |I know that a pointer to freed memory should never be dereferenced, 
  13. |but is it standard-conforming to assign or do arithmetic with such
  14. |pointers?
  15. |
  16. |The application is a routine to free the elements of a circular list.
  17. |Since I have a count of the elements, I can simply run a pair of pointers
  18. |around the list, like so:
  19. |
  20. |    for ( p = head, i = 0;  i < n;  i++ ) {
  21. |        q = p;
  22. |        p = p->next;
  23. |        free(q);
  24. |    }
  25. |
  26. |The question comes up because on the last iteration, p->next points
  27. |to the element freed in the first iteration.  Do I need to break the
  28. |circle before I start the loop? Or am I just being paranoid after the 
  29. |discussion of pointers to invalid array elements?
  30.  
  31. Erm, yes, I hate to say it, but you're getting paranoid ;-) 
  32.  
  33. As long as you do not dereference such a pointer (as you indicated
  34. yourself,) everything is fine.  If pointer q contained a valid pointer
  35. value _before_ the call to free(), it'll contain a valid pointer value
  36. _after_ the call. In the last iteration, the value p->next points to
  37. a location in memory where the first element of the list _would have
  38. been_ if it weren't freed in the first iteration. And, again, if you
  39. don't dereference that pointer value, everything is safe and sound.
  40.  
  41. kind regards,
  42.  
  43. Jos aka jos@and.nl
  44.