Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Referenced Annex J and tweajed wording for readability.

Variable-length arrays (VLA) are essentially the same as traditional C arrays, except that they are declared with a size that is not a constant integer expression, and may be declared only at block scope or function prototype scope and no linkage. A variable-length array can be declared as follows:

Code Block
{   /* block scope */
    char vla[ssize];
}

Wiki Markup
where the integer expression {{ssize}} and the declaration of {{vla}} are both evaluated at runtime. If athe size argument supplied to a variable-length array is not a positive integer value, the behavior is undefined (see [undefined behavior 69|CC. Undefined Behavior#ub_69] in Annex J of C99). reasonableIn sizeaddition, then if the magnitude of the argument is excessive 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 variable-length arrays are valid and have not been corrupted as the result of an exceptional integer condition.

...

In this noncompliant code example, a variable-length array of size s size 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.

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

However, it is unclear whether not guaranteed that the value of s size is a valid size argument. Depending on how variable-length arrays are implemented, the size may be interpreted as a negative value or a large positive value. The either case, a security vulnerability may occur, potentially giving rise to a security vulnerability.

Compliant Code Solution

This compliant solution ensures the size argument s used to allocate vla is in a valid range (between 1 and a programmer-defined maximum), otherwise it uses an algorithm that relies on dynamic memory allocation.

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

void func(size_t ssize) {
  if (s0 < MAX_ARRAYsize && ssize != 0< MAX_ARRAY) {
    int vla[ssize];
    /* ... */
  } else {
    /* Use Handledynamic errorallocation */
  }
}

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

Implementation Details

...