Out-of-bounds pointers

Wm E Davidsen Jr davidsen at crdos1.crd.ge.COM
Wed Oct 11 04:23:33 AEST 1989


In article <11232 at smoke.BRL.MIL>, gwyn at smoke.BRL.MIL (Doug Gwyn) writes:
|	[ read the original ]
|  
|  How could they?  If a computation produces a genuinely meaningless
|  result, how can a reasonable program rely on it?

  Consider: a program is going to read some LARGE number of values in
the range 30000-30006. It wants to count the number of occurences of
each value. Therefore:
	long ShortVect[10] = {0,0,0,0,0,0,0,0,0,0}, *Ptr, Val;
	
	Ptr = &ShortVect[-30000];
	while ((Val = MyRead()) > 0) Ptr[Val]++;

  Note that by creating the pointer to an invalid address we now can add
the value as a subscript. The address modified is *always* valid (if the
input is in range), the vector doesn't need to be 30007 in length, and
you don't have to subtract 30000 each time.

  I make no claim that this is the only way to do this, simple that
there are programs around which actually do use this trick (I saw it in
a net program). I submit that this is neither sloppy programming or
meaningless, and that it is "not illegal" by K&R 1st Ed. It's a trick to
save some space and CPU, something anyone on a small machine tries to do.

|  
|  was a MYSTERY (until I finally tracked it down).  If you think that
|  this is desirable behavior, then you're nuts.

  That's certainly keeping the discussion on a high technical plane.


|  >I fail to see what benefit is gained.
|  
|  The "benefit" is that faster, more natural C implementations are
|  permitted on architectures where this is an issue.

  Please identify the machines in question and quantify the saving.

|  
|  >Could someone clarify this, since it certainly is not prevailing
|  >practice? 
|  
|  I have no idea what you mean by "prevailing practice".  

  Prevailing practice means what it says, that before compilers were
modified to make it illegal such code would work on most machines, such
as Sun, Vax, PC, Cray, PDP-11, etc. I think that fairly represents at
least 80% of the machines and users running pre-ANSI C.
-- 
bill davidsen	(davidsen at crdos1.crd.GE.COM -or- uunet!crdgw1!crdos1!davidsen)
"The world is filled with fools. They blindly follow their so-called
'reason' in the face of the church and common sense. Any fool can see
that the world is flat!" - anon



More information about the Comp.std.c mailing list