Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!cs.utexas.edu!usc!apple!rutgers!cmcl2!phri!marob!daveh From: daveh@marob.masa.com (Dave Hammond) Newsgroups: comp.lang.c Subject: Pointer arithmetic and comparisons. Message-ID: <257ECDFD.CDD@marob.masa.com> Date: 7 Dec 89 20:54:19 GMT Sender: daveh@marob.masa.com Reply-To: daveh@marob.masa.com (Dave Hammond) Organization: ESCC, New York City Lines: 44 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@marob.masa.com