局部变长数组
Local variable length array
在 C++ 的一些代码重构过程中,我遇到了以下局部可变长度数组
void some_function(uint8_t length, uint8_t id, uint8_t * bytes)) {
uint8_t string[length + 8];
//some transformation on string [1-8] elements
do_something(string);
}
我不熟悉C99,但使用可变长度数组大小[x+y] 看起来这将被放置在堆中。我还调试了这个函数以确保这个 "string" 变量被放置在堆上并且确实如此。
在 C 中,局部变量不能固定大小,因此在使用后不需要清理它们。但是这里我们有没有内存分配的固定大小数组,所以不需要在这个变量之后清理,但是GCC编译器如何管理这个内存?
或者可能以其他方式澄清我在这里考虑的内容:长度变量来自外部 IO,所以在我看来可能存在安全问题(例如,当长度为 INTEGER_MAX 值时),此外检查长度的大小可以采取哪些其他措施来获得安全代码?或者它可能已经安全了?
您在此代码中看到的是 C99 Variable Length Array。一个类似的提议几乎进入了 C++14,但没有。所以这段代码不是有效的标准 C++,但你的编译器可能支持它。 AFAIK,C99 VLA 将它们的内存存储在堆栈中。
看到这个question and this one. It's a GCC extension:
Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The storage is allocated at the point of declaration and deallocated when the block scope containing the declaration exits.
在 C++ 的一些代码重构过程中,我遇到了以下局部可变长度数组
void some_function(uint8_t length, uint8_t id, uint8_t * bytes)) {
uint8_t string[length + 8];
//some transformation on string [1-8] elements
do_something(string);
}
我不熟悉C99,但使用可变长度数组大小[x+y] 看起来这将被放置在堆中。我还调试了这个函数以确保这个 "string" 变量被放置在堆上并且确实如此。 在 C 中,局部变量不能固定大小,因此在使用后不需要清理它们。但是这里我们有没有内存分配的固定大小数组,所以不需要在这个变量之后清理,但是GCC编译器如何管理这个内存?
或者可能以其他方式澄清我在这里考虑的内容:长度变量来自外部 IO,所以在我看来可能存在安全问题(例如,当长度为 INTEGER_MAX 值时),此外检查长度的大小可以采取哪些其他措施来获得安全代码?或者它可能已经安全了?
您在此代码中看到的是 C99 Variable Length Array。一个类似的提议几乎进入了 C++14,但没有。所以这段代码不是有效的标准 C++,但你的编译器可能支持它。 AFAIK,C99 VLA 将它们的内存存储在堆栈中。
看到这个question and this one. It's a GCC extension:
Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The storage is allocated at the point of declaration and deallocated when the block scope containing the declaration exits.