(char *)(-1)

Frans Meulenbroeks meulenbr at cstw01.prl.philips.nl
Tue Aug 1 19:32:35 AEST 1989


In article <1282 at cbnewsl.ATT.COM> dfp at cbnewsl.ATT.COM (david.f.prosser) writes:
>In article <1063 at tukki.jyu.fi> tarvaine at tukki.jyu.fi (Tapani Tarvainen) writes:
>>Is it safe to return -1?
>>I mean, isn't it possible that (char *)(-1) is a valid pointer
>>in some system and could have been returned by malloc(), or does
>>the pANS require it isn't?
>>
>>If -1 isn't safe, is there any other value (besides NULL) that can
>>safely be returned from a (any *) function to indicate error?
>
>(char *)-1 could well be a valid pointer returned by malloc().  The
>pANS has no guarantee about special pointer values except for the
>null pointer.
>
[rest deleted]

I agree that (char *) -1 could be a valid pointer.
However the chances that it will be are so incredibly small that I for me
would safely ignore this.

Consider the following:
If your system uses 2-s complement (most systems do) -1 would refer to
an address with all 1-s (e.g. 0xffffffff on a 32 bit system).
That is the very last address in the systems address space.
So (assuming 2-s complement) (char *) -1 can only be a valid
pointer if the following conditions are satisfied:
- there is memory on the last address in the system
  (not likely in the case of memory mapped I/O. Also not likely in 
   the case of 32 bit addresses, since this requires an awful lot
   of memory)
- people have done a malloc(0) (not useful IMHO) or a malloc(1)
  (otherwise there is just not enough memory to let the block
   start at the very last address)
- the system supports odd addresses

I don't think I've ever programmed a system since the intel 8008 which
satisfies these conditions. And the 8008 did not have a C compiler :-)

Frans Meulenbroeks        (meulenbr at cst.prl.philips.nl)
	Centre for Software Technology
	( or try: ...!mcvax!phigate!prle!cst!meulenbr)



More information about the Comp.std.c mailing list