Pointer arithmetic and comparisons.

Dave Hammond daveh at marob.masa.com
Fri Dec 8 07:54:19 AEST 1989


Machine/OS: 286-compatible/MSDOS
Compiler: Turbo-C 1.5

One method I use to avoid overflow while filling a buffer is to set a
pointer to the address of the last element (&buffer[last]), then compare
the current buffer position to the end pointer, testing that "current"
is never greater than "end".  An example fragment might be:

some_function(char *buffer, int len)
{
	char *p = buffer;
	char *e = &buffer[len];

	while ((*p++ = getchar()) != EOF && p < e) {
		...
		}

	...
}

This method has never bitten me on Unix/Xenix/*nix systems of any
flavor, on machines ranging from 286's to 68K's to Sparcs.  Now, in an
attempt to port to MSDOS/Turbo-C, this method breaks.

The problem occurs when the address resulting from &buffer[len] exceeds
65535.  For example, if &buffer[0] is 65535 and len is 100, &buffer[len]
becomes 99, making `while (p < e)' immediately false.

I was under the impression that (for n > 0) buffer[n] should not yield
an address lower than buffer[0].  Is the pointer comparison I am doing
non-portable, or otherwise ill-advised ?

BTW, I am well aware of alternate methods of checking for buffer
overflow, so please do not suggest alternatives.  I am interested in why
*this* method fails.

Respond via e-mail if you feel this is of little net-wide interest.
Post if you feel others might benefit.

Thanks in advance.

--
Dave Hammond
daveh at marob.masa.com



More information about the Comp.lang.c mailing list