局部可变长度数组 [英] Local variable length array

查看:89
本文介绍了局部可变长度数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中进行一些代码重构期间,我遇到了以下局部可变长度数组

during some code refactor in C++ i meet following local variable length arrays

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]看起来会放在堆中.另外,我调试此函数以确保将此字符串"变量放置在堆上并且放置在堆上. 在C语言中,局部变量不能固定大小,因此在使用它们后不需要清理它们.但是这里我们有固定大小的数组,没有分配内存,因此不需要在此变量之后进行清理,而是GCC编译器如何管理此内存?

I am not familiar with C99 but using Variable-length array size [x+y] look like this will be placed in heap. Also I debug this function to make sure that this "string" variable is placed on heap and it is. In C local variables can't be fixed size, so they are not needed to clean up after using them. But here we have fixed size array without memory allocation, so is no need to clean up after this variable, but how GCC compiler manage this memory?

或者也许以其他方式澄清我在这里考虑的内容:length变量来自外部IO,所以我认为可能存在安全性问题(例如,当length为INTEGER_MAX值时),此外还要检查length的大小可以采取其他措施在此处获得安全代码吗?也许它已经安全了?

Or maybe on other way to clarifying what I am considering here: length variable is coming from external IO so in my opinion there can be security issue (for example when length will be INTEGER_MAX value), besides check the size of length what other actions can be taken to have secure code here? Or maybe it is already secure?

推荐答案

在此代码中看到的是C99

What you see in this code is a C99 Variable Length Array. A similar proposal almost made it to C++14, but didn't. So this code is not valid STANDARD C++, but your compiler may support it. AFAIK, C99 VLAs store their memory on the stack.

这篇关于局部可变长度数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆