Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!cs.utexas.edu!samsung!munnari.oz.au!murtoa.cs.mu.oz.au!ditmela!yarra!bohra!ejp From: ejp@bohra.cpg.oz (Esmond Pitt) Newsgroups: comp.lang.c Subject: Re: Pointer arithmetic and comparisons. Message-ID: <232@bohra.cpg.oz> Date: 10 Dec 89 23:47:58 GMT References: <257ECDFD.CDD@marob.masa.com> Reply-To: ejp@bohra.UUCP (Esmond Pitt) Organization: Computer Power Group, Melb, Australia Lines: 31 In article <257ECDFD.CDD@marob.masa.com> daveh@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@bohra.cpg.oz