🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c
Article #5747

Re: detecting invalid pointers

#5747
From: Karl Heuer
Date: Thu, 09 Mar 1989 19:29
20 lines
1469 bytes
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
Technical Details
Message-ID: <11998@haddock.ima.isc.com>
Path: arc1-ca.pugleaf.net!utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!tut.cis.ohio-state.edu!ucbvax!decwrl!decvax!ima!haddock!karl
References: <15495@cup.portal.com>

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!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