4

I have a series of about 30 functions which use local arrays as such:

void foo() {
  const int array_size = 32;
  char my_array[array_size];

  // .. do stuff
  // (array_size is used multiple times)
}

The code (when compiling with -Wstack-protector) will produce the following warning message:

warning: stack protector not protecting local variables: variable length buffer

So I have two questions:

First, why is my_array considered variable length? Yea, I know why technically, but shouldn't the compiler be smart enough to realize that it isn't really variable length?

Second, what is the most appropriate way to fix this warning? I know I can fix it by doing something like:

void foo() {
  char my_array[32];
  const int array_size = sizeof(my_array) / sizeof(my_array[0]);

  // .. do stuff
  // (array_size is used multiple times)
}

but is there a better, more "correct" way?

amurka
  • 645
  • 1
  • 6
  • 14

2 Answers2

3
const int array_size = 32;

Does NOT make array_size a constant. It merely means that it cannot be used for assignment as an lvalue. (it's value can be changed otherwise). Therefore it is not allowed as a constant literal in:

char my_array[array_size];

You can either:

#DEFINE array_size  32

or

enum { array_size = 32 };
David C. Rankin
  • 81,885
  • 6
  • 58
  • 85
  • 2
    No, its value cannot be changed otherwise. Whether it is "a constant" depends on your definition of that term. It is `const`, it is not writable, it is not an *integer constant expression*. – M.M Aug 27 '14 at 00:02
-1

You probably should allocate dynamically your array as:

void foo() {
  const int array_size = 32;
  char *my_array;
  my_array = malloc((array_size)*sizeof(char));
  // .. do stuff
  // (array_size is used multiple times)

  free(my_array);
}
Cléber Oliveira
  • 119
  • 1
  • 1
  • 8