detecting invalid pointers

Karl Heuer karl at haddock.ima.isc.com
Fri Mar 10 05:29:40 AEST 1989


In article <15495 at cup.portal.com> Kevin_P_McCarty at 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 at haddock.isc.com), The Walking Lint



More information about the Comp.lang.c mailing list