Xref: utzoo comp.std.c:880 comp.lang.c:16826 Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!ucbvax!decwrl!decvax!ima!haddock!karl From: karl@haddock.ima.isc.com (Karl Heuer) Newsgroups: comp.std.c,comp.lang.c Subject: Re: detecting invalid pointers Message-ID: <11998@haddock.ima.isc.com> Date: 9 Mar 89 19:29:40 GMT References: <15495@cup.portal.com> Reply-To: karl@haddock.ima.isc.com (Karl Heuer) Distribution: usa Organization: Interactive Systems, Boston Lines: 20 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. If you want to do it in constant time rather than linear, then the answer is No. 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). So if you absolutely have to do this, just add a bunch of #ifdef's (and a big comment, in a blinking font) to the within() routine above. Karl W. Z. Heuer (ima!haddock!karl or karl@haddock.isc.com), The Walking Lint