Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

In this non-compliant code example, a VLA of size s is declared. The size s is declared as size_t in compliance with INT01-A. 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. Depending on how VLAs are implemented, s may be interpreted as a negative value or a very large positive value. In either case, this may result in a security vulnerability.

Code Block
bgColor#FFCCCC
void func(size_t s) {
  int vla[s];
  /* ... */
}
/* ... */
func(size);
/* ... */


However, it is unclear whether the value of s is a valid size argument. Depending on how VLAs are implemented, the size may be interpreted as a negative value or a very large positive value. In either case, this may result in a security vulnerability.

Compliant Code Solution

Validate size arguments used in VLA declarations. The solution below ensures the size argument, s, used to allocate vla is in a valid range: 1 to a user-defined constant.

Code Block
bgColor#ccccff
enum { MAX_ARRAY = 1024 };

void func(size_t s) {
  if (s < MAX_ARRAY && s != 0) {
    int vla[s];
    /* ... */
  } else {
    /* Handle Error */
  }
}

/* ... */
func(size);
/* ... */

Implementation Details

Microsoft

Variable length arrays are not supported by Microsoft compilers.

GCC

Newer versions of GCC have incorporated variable length arrays, but do not yet claim full C99 conformance. As such, variable length arrays should only be used on GCC with great care.

On an example Debian GNU/Linux Intel 32-bit test machine with GCC v. 4.2.2, 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.

Risk Assessment

Failure to properly specify the size of a variable length array may allow arbitrary code execution or result in stack exhaustion.

...