[cfe-dev] -Warray-bounds seems over-zealous on Clang

Douglas Gregor dgregor at apple.com
Tue Jul 12 08:02:45 PDT 2011


On Jul 12, 2011, at 7:46 AM, Peter Geoghegan wrote:

> Hello,
> 
> Consider the common idiom in C, of a struct with its last declared
> type is an array like this:
> 
> typedef struct
> {
>        int id;
>        int values[1];
> } my_struct;
> 
> This will be stored in dynamically allocated memory. Memory will be
> allocated for my_struct, in addition to however many additional
> integers must be stored. Despite how frequently this is seen, Clang
> doesn't seem to like this. In particular, it over-zealously complains
> about assigning past the end of "values" when that can be statically
> determined (because an int rvalue is used), when the -Warray flag is
> given. GCC, on the other hand, does not. This is of particular concern
> when hacking on the PostgreSQL code, that makes extensive use of this
> idiom:
> 
> /home/peter/build/Release/bin/clang -O2 -Wall -Wmissing-prototypes
> -Wpointer-arith -Wdeclaration-after-statement -Wendif-labels
> -Wformat-security -fno-strict-aliasing -fwrapv -I../../../src/include
> -D_GNU_SOURCE   -c -o namespace.o namespace.c
> namespace.c:1497:29: warning: array index of '1' indexes past the end
> of an array (that contains 1 elements) [-Warray-bounds]
>                                                operform->oprright ==
> resultList->args[1])
> 
> ^                ~
> ../../../src/include/catalog/namespace.h:37:2: note: array 'args' declared here
>        Oid                     args[1];                /* arg types
> --- VARIABLE LENGTH ARRAY */
>        ^
> namespace.c:1509:30: warning: array index of '1' indexes past the end
> of an array (that contains 1 elements) [-Warray-bounds]
> 
> operform->oprright == prevResult->args[1])
> 
>       ^                ~
> ../../../src/include/catalog/namespace.h:37:2: note: array 'args' declared here
>        Oid                     args[1];                /* arg types
> --- VARIABLE LENGTH ARRAY */
>        ^
> namespace.c:1540:3: warning: array index of '1' indexes past the end
> of an array (that contains 1 elements) [-Warray-bounds]
>                newResult->args[1] = operform->oprright;
>                ^               ~
> ../../../src/include/catalog/namespace.h:37:2: note: array 'args' declared here
>        Oid                     args[1];                /* arg types
> --- VARIABLE LENGTH ARRAY */
>        ^
> 
> This seems like a bug to me. What's the consensus view on this?

I suggest using a C99 flexible array member, e.g.,

> typedef struct
> {
>        int id;
>        int values[];
> } my_struct;

which is designed for specifically this use case.

	- Doug




More information about the cfe-dev mailing list