Pointer arithmetic and comparisons.

Esmond Pitt ejp at bohra.cpg.oz
Mon Dec 11 10:47:58 AEST 1989


In article <257ECDFD.CDD at marob.masa.com> daveh at marob.masa.com (Dave Hammond) writes:
>
>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" ...
>
>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.

That's because the last element is not &buffer[last] but &buffer[last-1],
and so you should test for <= &buffer[last-1], not < &buffer[last].
You are incrementing a pointer to point outside the object, and this is
not guaranteed to work under _any_ implementation of C. Your code
should read:

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

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

	...
}
-- 
Esmond Pitt, Computer Power Group
ejp at bohra.cpg.oz



More information about the Comp.lang.c mailing list