[antlr-interest] [C runtime] don't compare pointer for negative return values !

Gavin Lambert antlr at mirality.co.nz
Fri Aug 24 05:22:13 PDT 2007


At 23:26 24/08/2007, Holger Schurig wrote:
 >Second: the return value for antlr3AsciiFileStreamNew() is a
 >pointer. Comparing this for < 0 is nonsense again, because the
 >c-runtime could as well give you back 0xD00C0020 as address for
 >this pointer. This, seen as a signed value, would be smaller
 >than zero. Yet the object has been successfully created.

This one annoyed me a bit too.  The workaround I tend to use is to 
define this at the top of my program:

#define ANTLR_FAILED(x)		((int)(x) < 0 && (int)(x) > -100)

This is a bit crude, but permits up to 100 different error levels 
(arbitrarily chosen number) while reducing the possibility of 
collision with a real pointer value.  (The chances of getting a 
pointer at 0xFFFFFFxx are vanishingly small.)

Make sure you only pass it a pointer variable, though -- don't 
wrap it around a function call directly or it'll end up invoking 
the function twice.  (gcc provides a syntax that can be used to 
avoid this effect, but sadly it's not portable.)


I tend to agree with you, though.  The normal behaviour for 
anything that returns a pointer should be to return NULL on 
failure, with (if necessary) a call to an additional function if 
you really care about the error code involved.  Or an output 
parameter, though those are a bit ugly too.



More information about the antlr-interest mailing list