1

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

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?

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?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
  • Pretty much every sentence here is somehow wrong (to start with, you seem to confuse "fixed size" and "variable-sized"). Please read a good book. – deviantfan Jun 07 '15 at 13:45
  • 2
    C++ doesn't have [variable length arrays](http://en.wikipedia.org/wiki/Variable-length_array), so technically that code is not valid C++. – Some programmer dude Jun 07 '15 at 13:46

2 Answers2

2

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.

Ophir Gvirtzer
  • 604
  • 4
  • 8
  • I just checked the addresses and it is with same place when structures that uses malloc. I am on ARM Cortex-M3 platform (so stack start at 0x080.. and heap on 0x200..) –  Jun 07 '15 at 14:05
1

See this 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.

Community
  • 1
  • 1