After reading [1] I wonder whether Gnulib should define, in some header file,
these macros:

  #define ARRAY_OF_EXACTLY(a,n) (*a)[n]
  #define ARRAY_OF_AT_LEAST(a,n) a[static n]

So that functions may be declared and defined as taking a parameter
  TYPE ARRAY_OF_EXACTLY (PARAMETER, SIZE)
or
  TYPE ARRAY_OF_AT_LEAST (PARAMETER, LOWER_BOUND_FOR_SIZE)

This may be useful, because it enables gcc warnings (see attachment).
On the other hand
  - ARRAY_OF_EXACTLY requires writing an indirection (that is in fact a no-op),
  - ARRAY_OF_AT_LEAST is sometimes mis-used.

Hmm. What do you think?

Bruno

[1] https://lwn.net/Articles/1046840/
#define ARRAY_OF_EXACTLY(a,n) (*a)[n]
#define ARRAY_OF_AT_LEAST(a,n) a[static n]

int foo10 (int a[10]) { return a[1] - a[10]; }
int foo11 (int a[11]) { return a[1] - a[10]; }
int foo20 (int ARRAY_OF_AT_LEAST(a,10)) { return a[1] - a[10]; }
int foo21 (int ARRAY_OF_AT_LEAST(a,11)) { return a[1] - a[10]; }
int foo30 (int ARRAY_OF_EXACTLY(a,10)) { return (*a)[1] - (*a)[10]; } // clang warns
int foo31 (int ARRAY_OF_EXACTLY(a,11)) { return (*a)[1] - (*a)[10]; }

int main ()
{
  {
    int data[10];
    foo10 (data);
    foo11 (data); // gcc warns
    foo20 (data);
    foo21 (data); // gcc warns, clang warns
    foo30 (&data);
    //foo31 (&data); // error: different size
  }
  {
    int data[11];
    foo10 (data);
    foo11 (data);
    foo20 (data);
    foo21 (data);
    //foo30 (&data); // error: different size
    foo31 (&data);
  }

  return 0;
}

/*
 * gcc -Wall -Warray-parameter=2 -Warray-bounds=2 -Wstringop-overflow=4 foo.c
 * clang -Wall -Warray-parameter -Warray-bounds foo.c
 */

Reply via email to