[Gllug] Pointer arithmetic with void *

Nix nix at esperi.demon.co.uk
Sun Aug 18 18:51:25 UTC 2002


On Wed, 14 Aug 2002, Alain Williams mused:
> On Wed, Aug 14, 2002 at 04:15:06PM +0100, Tethys wrote:
>> 	ptr = mmap(NULL, 1024, PROT_READ, MAP_SHARED, fd, 0);
>> 	ptr++;
>> 
>> Where is ptr pointing? 1 byte from the start of the file? One
>> "pointer length" (i.e., 4 or 8 bytes from the start of the file)?
>> Something else entirely?
>> 
>> Empirical evidence shows it to be a 1 byte increment on Linux and
>> Solaris, but can this be relied upon, or is it just an implementation
>> detail of gcc (which I used on both)? K&R doesn't say either way, and
>> I don't want to be making assumptions that may prove non-portable.
> 
> You can't do it, it is illegal. The point is that on a byte addressed m/c

Rather, it is undefined.

> (like most that you are used to)
> 	ptr++
> compiles to:
> 	ptr += sizeof(*ptr)
> Since void* doesn't point to anything in particular it doesn't know what *ptr
> is and so doesn't know how big it is. [[It get more interesting with m/cs with
> other addressing schemes]].
> 
> If gcc is allowing this, it is breaking the standard. Try compiling with the

No, it is a documnted extension. See the `Pointer Arith' page in the GCC
info documentation (under `C Extensions').

This extension was, I agree, probably a mistake.

As such, the extension is rejected when -ansi, -std=c89 or anything
equivalent to it, or -std=c99 or anything equivalent to that is
provided; also, -Wpointer-arith warns about such things.

-- 
`Mips are real and bitrate earnest, shifting spam is not our goal;
 silicon to sand returnest, was not spoken of the soul.'
   --- _Eventful History: Version 1.x_, John M. Ford

-- 
Gllug mailing list  -  Gllug at linux.co.uk
http://list.ftech.net/mailman/listinfo/gllug




More information about the GLLUG mailing list