This is the mail archive of the gcc-bugs@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

[Bug c/22485] pointer +- integer is never NULL


------- Additional Comments From gdr at gcc dot gnu dot org  2005-09-24 05:37 -------
(In reply to comment #0)
> The code
> 
> void stuff(void);
> void f(int *p, int x)
> {
>         int *q = p + x;
>         if (!q)
>                 stuff();
> }
> 
> should never call stuff() - the test is unnecessary since pointer +/- integer is
> undefined when the pointer does not point to an object or just past the end of
> one (6.5.6 paragraph 8). This is important in cases such as:
> 
> static inline struct foo *lookup(struct foo *table, int x)
> {
>     if (match(table, x))
>         return table + x;
>     else
>         return NULL;
> }
> ...
>     struct foo *e = lookup(tbl, x);
>     if (e) ...
> 
> The code that calls the above function ends up checking for NULL twice: once
> inside the (inlined) function, and one after the call. Were Q = P +- I
> recognised as implying that P != NULL, Q != NULL (as we are allowed to do
> according to the Standard), then the extraneous NULL test could be eliminated.


There have been lots of messages exchanged on this topic.  It was just
pointed to me that the C++ standard -- unlike the C99 standard -- has the
following wording 5.7/7:

   If the value 0 is added to or subtracted from a pointer value, the result
   compares equal to the original pointer value. If two pointers point to the
   same object or both point one past the end of the same array or both are
   null, and the two pointers are subtracted, the result compares equal to the
   value 0 converted to the type ptrdiff_t.
  
-- Gaby

  

   

-- 


http://gcc.gnu.org/bugzilla/show_bug.cgi?id=22485


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]