Variable-length arrays (VLAs) are essentially the same as traditional C arrays, the major difference being that they are declared with a size that is not a constant integer expression. A variable-length array can be declared as follows:
Code Block |
---|
char vla[s]; |
Wiki Markup |
---|
Wherewhere the integer {{s}} and the declaration are both evaluated at runtime. If a size argument supplied to VLAs a variable-length array is not a positive integer value of reasonable size, then the program may behave in an unexpected way. An attacker may be able to leverage this behavior to overwrite critical program data \[[Griffiths 06|AA. C References#Griffiths 06]\]. The programmer must ensure that size arguments to VLAsvariable-length arrays are valid and have not been corrupted as the result of an exceptional integer condition. |
...
In this noncompliant code example, a VLA variable-length array of size s
is declared. The size s
is declared as size_t
in compliance with INT01-C. Use rsize_t or size_t for all integer values representing the size of an object.
...
However, it is unclear whether the value of s
is a valid size argument. The size s
could have the value 0. And, depending on how VLAs Depending on how variable-length arrays are implemented, the size may be interpreted as a negative value or a very large positive value. The either case, in particular a value too large for the array to be properly allocated. In either case, this may result in a security vulnerabilitya security vulnerability may occur.
For example, for GCC 4.2.2 on the Debian GNU/Linux Intel 32-bit platform, the value of a variable length array's size is interpreted as a 32-bit signed integer. Passing in a negative number for the size will likely cause the program stack to become corrupted, and passing in a large positive number may cause a terminal stack overflow. It is important to note that this information may become outdated as GCC evolves.
Compliant Code Solution
Validate size arguments used in VLA declarations. The solution below This compliant solution ensures the size argument , s
, used to allocate vla
is in a valid range : (between 1 to and a userprogrammer-defined constantmaximum).
Code Block | ||
---|---|---|
| ||
enum { MAX_ARRAY = 1024 }; void func(size_t s) { if (s < MAX_ARRAY && s != 0) { int vla[s]; /* ... */ } else { /* Handle Error */ } } /* ... */ func(size); /* ... */ |
...