One common mistake in C is to do sizeof(x) where x is a pointer and
what was really wanted was sizeof(*x).  Similar to requiring
parentheses around assignments in conditionals, I'd like an optional
warning to be added when sizeof is done on a variable that is a
pointer.  For example, in the code below, the first sizeof would
give a warning.  To prevent this warning, sizeof(char *) can be
used instead.

void fu (void)
{   
    char *x;
    printf(" x %d\n", sizeof(x));
    printf("char * %d\n", sizeof(char *));
    printf("char * %d\n", sizeof("hello world"));
}

I've done a proof of concept for gcc 3.3 as below.  I haven't done             
extensive testing and I didn't make the warning optional.

*** c-parse.y   2005/12/05 22:19:42     1.1
--- c-parse.y   2005/12/05 22:54:43
***************
*** 494,502 ****
--- 494,506 ----  
                  if (TREE_CODE ($2) == COMPONENT_REF
                      && DECL_C_BIT_FIELD (TREE_OPERAND ($2, 1)))
                    error ("`sizeof' applied to a bit-field");
+                   warning("`sizeof' reference #1");
+                   if (TREE_CODE (TREE_TYPE ($2)) == POINTER_TYPE)
+                     warning("`sizeof' applied to a pointer variable");
                  $$ = c_sizeof (TREE_TYPE ($2)); }
        | sizeof '(' typename ')'  %prec HYPERUNARY
                { skip_evaluation--;
+                   warning("`sizeof' reference #2");
                  $$ = c_sizeof (groktypename ($3)); }
        | alignof unary_expr  %prec UNARY
                { skip_evaluation--;


-- 
           Summary: feature request: generate a warning for sizeof on a
                    pointer
           Product: gcc
           Version: 4.2.0
            Status: UNCONFIRMED
          Severity: enhancement
          Priority: P3
         Component: c
        AssignedTo: unassigned at gcc dot gnu dot org
        ReportedBy: meklund at cisco dot com


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


Reply via email to