[cfe-dev] About void* arithmetic and dereferencing.

Enea Zaffanella zaffanella at cs.unipr.it
Sun Aug 22 06:06:14 PDT 2010


Hello.

I am a bit confused regarding clang behavior wrt the support of void* 
arithmetic and dereferencing extensions.
It looks as if clang is treating differently syntactic constructs that 
(afaict) should be regarded as semantically equivalent.

Consider the following program fragment:

===========================
void* bar(void);

unsigned foo(void) {
   unsigned u = 0;
   void* p;
   p = bar();
   p += 8;
   p = &p[8]; /* Equivalent to previous line (?) */

   u += sizeof(*p);
   u += sizeof(p[0]); /* Equivalent to previous line (?) */
   return u;
}
===========================

When compiled using gcc and -Wpointer-arith, we get:
===========================
gcc -Wpointer-arith -c bug.c -o /dev/null
bug.c: In function ‘foo’:
bug.c:7: warning: pointer of type ‘void *’ used in arithmetic
bug.c:8: warning: pointer of type ‘void *’ used in arithmetic
bug.c:8: warning: dereferencing ‘void *’ pointer
bug.c:10: warning: invalid application of ‘sizeof’ to a void type
bug.c:11: warning: pointer of type ‘void *’ used in arithmetic
bug.c:11: warning: invalid application of ‘sizeof’ to a void type
===========================

If instead we use clang (r111514), some of these warnings (i.e., the 
ones on the lines ending in a comment) are mapped to errors:
===========================
$ clang -Wpointer-arith -fsyntax-only bug.c
bug.c:7:5: warning: use of GNU void* extension [-Wpointer-arith]
   p += 8;
   ~ ^  ~
bug.c:8:9: error: subscript of pointer to incomplete type 'void'
   p = &p[8]; /* Equivalent to previous line (?) */
        ~^
bug.c:10:8: warning: invalid application of 'sizeof' to a void type
       [-Wpointer-arith]
   u += sizeof(*p);
        ^     ~~~~
bug.c:11:16: error: subscript of pointer to incomplete type 'void'
   u += sizeof(p[0]); /* Equivalent to previous line (?) */
               ~^
2 warnings and 2 errors generated.
===========================

This behavior seems to be inconsistent wrt C99 6.5.2.1p2,
where it is said that E1[E2] is identical to (*((E1)+(E2))).

Is this just something that has to be fixed, or are there other reason 
explaining the currently observed behavior?

Regards,
Enea.




More information about the cfe-dev mailing list