简体   繁体   English

修复堆栈保护程序的正确方法是什么:可变长度缓冲区警告?

[英]What's the correct way to fix stack protector: variable length buffer warning?

I have a series of about 30 functions which use local arrays as such: 我有一系列约30个使用本地数组的函数:

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: 代码(使用-Wstack-protector编译时)将产生以下警告消息:

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

So I have two questions: 所以我有两个问题:

First, why is my_array considered variable length? 首先,为什么my_array被认为是可变长度? 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? 但是有更好,更“正确”的方式吗?

const int array_size = 32;

Does NOT make array_size a constant. 使array_size成为常量。 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: 因此,它不允许作为constant literal

char my_array[array_size];

You can either: 你可以:

#DEFINE array_size  32

or 要么

enum { array_size = 32 };

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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM