Out-of-bounds pointers

Scott Amspoker scott at bbxsda.UUCP
Sat Oct 7 06:44:11 AEST 1989


In article <868 at crdos1.crd.ge.COM> davidsen at crdos1.UUCP (bill davidsen) writes:
>|  Doug Gwyn:
>|  
>|  > It's not even "legal" to compute an invalid address, whether or not
>|  > it is dereferenced.
>  While this is obviously true, I have never understood the rationale of
>this decision. Given that (a) there are existing programs which do this,
>for reasons other than sloppy programming, (b) most implementations
>happily allow this, and (c) if you are allowed to declare an auto
>pointer at all then obviously the hardware supports uninitialized
>pointers, I fail to see what benefit is gained.

We just got through an *extremely* long thread in comp.lang.c regarding
this issue (it eventually just fizzled out).  The basic idea is that a
pointer variable containing a bad (or uninitialized) address could be
loaded into an address register which, on some architectures, could
cause a "bad address" trap.  For example, the 286/386 CPUs will trap
if you load just any 'ol garbage into a segment register.  Since
handling a pointer variable might cause such a load operation you
could get a trap even though you did not de-reference the pointer.

This bothered many readers while other readers attempted to jusitfy
such an "implementation specific" detail.  What was once bad coding
style now was considered a bug.  Take the following code fragment as
an example:

my_proc()
   {
   register char *p;

   p = (char*)malloc(1000);
   free(p);  /* free never returns but core dumps instead - why? */
   }

This seemingly innocent code could possibly error out according to the
"rules of comformance" presented by some readers.  Here's why:

   a) pointer p is possibly in an address register which might be
      sensitive to bad addresses.

   b) p is assigned a valid address by malloc() - no problem.

   c) the free() call may return the freed memory block to the host
      system.  It was agreed that a conforming implementation had
      that right.  Therefore, the address in p might no longer be
      part of the process's address map and therefore invalid.

   d) Upon return from free() the (now invalid) value in p is popped
      off the stack back into its address register and... TRAP!

Don't worry - all is not lost.  No one was able to come up with a real
world example of something like this.  In other words - standards and
ANSI drafts aside - you probably will not get into trouble unless you
actually try to *de-reference* a bad pointer.

-- 
Scott Amspoker
Basis International, Albuquerque, NM
(505) 345-5232



More information about the Comp.std.c mailing list