Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!csd4.milw.wisc.edu!bbn!oberon!nunki.usc.edu!jeenglis From: jeenglis@nunki.usc.edu (Joe English) Newsgroups: comp.lang.c Subject: Re: detecting invalid pointers Message-ID: <3011@nunki.usc.edu> Date: 11 Mar 89 00:42:04 GMT References: <15495@cup.portal.com> <11998@haddock.ima.isc.com> Reply-To: jeenglis@nunki.usc.edu (Joe English) Distribution: usa Organization: University of Southern California, Los Angeles, CA Lines: 63 karl@haddock.ima.isc.com (Karl Heuer) writes: >In article <15495@cup.portal.com> Kevin_P_McCarty@cup.portal.com writes: >>Is there any guaranteed way to detect an out of range pointer, >>i.e., one which is supposed to point into an array but might not? > >Yes (my distinguished colleagues to the contrary notwithstanding): > int within(void *ptr, void *a, size_t n) { > char *p; > for (p = (char *)a; p < (char *)a + n; ++p) { > if ((char *)ptr == p) return (1); > } > return (0); > } >This works because pointer *equality* is well-defined even on pointers into >different arrays. Well, maybe not... Take, for example, the (you guessed it) 80x86 series in 'large' model, where pointers aren't normalized. It's then possible for two pointers to point to the same location yet have different segment:offset pair values. Most '86 compilers will *not* get this comparison right, since pointers are in general not normalized before comparisons to save time and space. >However, on any given implementation there ought to be >an unportable way (e.g., with a type pun followed by one or more integer >compares). Right -- in Microsoft/Turbo C a cast to 'huge *' should do the trick. On most reasonable architectures the code above ought to work (but it's still nonportable.) \begin{IMHO} In My Opinion, you should never *have* to check a raw pointer for validity. Any code that might possibly generate an out-of-range pointer should check the subscript (or loop count, or whatever) beforehand. I wouldn't bother to validate pointers inside, say, a utility routine either (other than checking for non-NULL), because it takes space and time and, quite frankly, it's the caller's responsibility not to pass bad pointers around. \begin{VeryBiasedOpinion} Range-checking and pointer validation are for programmers who are afraid that they might shoot themselves in the foot. Correct code will avoid generating bad pointers (among other things) in the first place. True, this is easier said than done -- but writing correct code is much more worth the effort than inserting runtime checks all over the place. \end{VeryBiasedOpinion} By the way, I don't practice what I preach as often as I should. \end{IMHO} --Joe English jeenglis@nunki.usc.edu