Versions Compared

Key

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

Variable length arrays (VLAs), a conditionally supported language feature, are essentially the same as traditional C arrays except that they are declared with a size that is not a constant integer expression and can be declared only at block scope or function prototype scope and no linkage. A variable When supported, a variable length array can be declared

Code Block
{   /* blockBlock scope */
    char vla[size];
}

where the integer expression size and the declaration of vla are both evaluated at runtime. If the size argument supplied to a variable length array is not a positive integer value, the behavior is undefined. (See undefined behavior 75 in Annex J of the C Standard [ISO/IEC 9899:2011].) In addition  Additionally, 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 2006]. The programmer must ensure that size arguments to variable length arrays, especially those derived from untrusted data, are in a valid range.

Because variable length arrays are a conditionally supported feature of C11, their use in portable code should be guarded by testing the value of the macro __STDC_NO_VLA__. Implementations that do not support variable length arrays indicate it by setting __STDC_NO_VLA__ to the integer constant 1.

Noncompliant Code Example

...

Code Block
bgColor#FFCCCC
langc
#include <stddef.h>

extern void do_work(int *array, size_t size);
 
void func(size_t size) {
  int vla[size];
  /* ... */do_work(vla, size);
}

However, it is not guaranteed that the value of size is a valid size argument may be zero or excessive, potentially giving rise to a security vulnerability.

Compliant

...

Solution

This compliant solution ensures the size argument 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:. The solution also avoids unsigned integer wrapping that, given a sufficiently large value of size, would cause malloc to allocate insufficient storage for the array.

Code Block
bgColor#ccccff
langc
#include <stdint.h>
#include <stdlib.h>
 
enum { MAX_ARRAY = 1024 };
extern void do_work(int *array, size_t size);
 
void func(size_t size) {
  if (0 == size || SIZE_MAX / sizeof(int) < size && ) {
    /* Handle error */
    return;
  }
  if (size < MAX_ARRAY) {
    int vla[size];
    do_work(vla, size);
  }  /* ... */
  } else {
else {
    int *array = (int *)malloc(size * sizeof(int));
    if (array == NULL) {
      /* UseHandle dynamic allocationerror */
    }
    do_work(array, size);
    free(array);
  }
}

Implementation Details

Microsoft

Variable length arrays are not supported by Microsoft compilers.

GCC

Variable length arrays should be used on GCC with great care. Newer versions of GCC have incorporated variable length arrays but do not yet claim full C conformance. GCC has limited incomplete support for parts of this standard, enabled with -std=c11 or -std=iso9899:2011.

Noncompliant Code Example (sizeof)

The following noncompliant code example defines A to be a variable length array and then uses the sizeof operator to compute its size at runtime. When the function is called with an argument greater than SIZE_MAX / (N1 * sizeof (int)), the runtime sizeof expression may wrap around, yielding a result that is smaller than the mathematical product N1 * n2 * sizeof (int). The call to malloc(), when successful, will then allocate storage for fewer than n2 elements of the array, causing one or more of the final memset() calls in the for loop to write past the end of that storage.

Code Block
bgColor#FFCCCC
langc
#include <stdlib.h>
#include <string.h>
 
enum { N1 = 4096 };

void *func(size_t n2) {
  typedef int A[n2][N1];

  A *array = malloc(sizeof(A));
  if (!array) {
    /* Handle error */
    return NULL;
  }

  for (size_t i = 0; i != n2; ++i) {
    memset(array[i], 0, N1 * sizeof(int));
  }

  return array;
}

Furthermore, this code also violates ARR39-C. Do not add or subtract a scaled integer to a pointer, where array is a pointer to the two-dimensional array, where it should really be a pointer to the latter dimension instead. This means that the memset() call does out-of-bounds writes on all of its invocations except the first.

Compliant Solution (sizeof)

This compliant solution prevents sizeof wrapping by detecting the condition before it occurs and avoiding the subsequent computation when the condition is detected. The code also uses an additional typedef to fix the type of array so that memset() never writes past the two-dimensional array.

Code Block
bgColor#ccccff
langc
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
 
enum { N1 = 4096 };

void *func(size_t n2) {
  if (n2 > SIZE_MAX / (N1 * sizeof(int))) {
    /* Prevent sizeof wrapping */
    return NULL;
  }

  typedef int A1[N1];
  typedef A1 A[n2];

  A1 *array = (A1*) malloc(sizeof(A));

  if (!array) {
    /* Handle error */
    return NULL;
  } 

  for (size_t i = 0; i != n2; ++i) {
    memset(array[i], 0, N1 * sizeof(int));
  }
  return array;
}

Implementation Details

Microsoft

Variable length arrays are not supported by Microsoft compilersOn an example Debian GNU/Linux Intel 32-bit test machine with GCC 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.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

ARR32-C

high

High

probable

Probable

high

High

P6

L2

Automated Detection

Tool

Version

Checker

Description

CodeSonar
Include Page
CodeSonar_V
CodeSonar_V

ALLOC.SIZE.IOFLOW
ALLOC.SIZE.MULOFLOW
MISC.MEM.SIZE.BAD

Integer Overflow of Allocation Size
Multiplication Overflow of Allocation Size
Unreasonable Size Argument

Coverity
Include Page
Coverity
6.5
_V
Coverity_V
REVERSE_NEGATIVEFully
Implemented
implemented
Cppcheck

Include Page
Cppcheck_V
Cppcheck_V

negativeArraySize

Context sensitive analysis
Will warn only if given size is negative

Cppcheck Premium

Include Page
Cppcheck Premium_V
Cppcheck Premium_V

negativeArraySize

premium-cert-arr32-c

Context sensitive analysis
Will warn only if given size is negative
Helix QAC

Include Page
Helix QAC_V
Helix QAC_V

C1051
Klocwork
Include Page
Klocwork_V
Klocwork_V

MISRA.ARRAY.VAR_LENGTH.2012


LDRA tool suite
 
Include Page
LDRA_V
LDRA_V
621 SEnhanced enforcement
Parasoft C/C++test

Include Page
Parasoft_V
Parasoft_V

CERT_C-ARR32-a

Ensure the size of the variable length array is in valid range

PC-lint Plus

Include Page
PC-lint Plus_V
PC-lint Plus_V

9035

Assistance provided

Polyspace Bug Finder

Include Page
Polyspace Bug Finder_V
Polyspace Bug Finder_V

CERT C: Rule ARR32-C

Checks for:

  • Memory allocation with tainted size
  • Tainted size of variable length array

Rule fully covered.

TrustInSoft Analyzer

Include Page
TrustInSoft Analyzer_V
TrustInSoft Analyzer_V

alloca_boundsExhaustively verified.
PRQA QA-C Include PagePRQA_VPRQA_V1051Partially implemented

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Related Guidelines

Key here (explains table format and definitions)

Taxonomy

Taxonomy item

Relationship

CERT C Secure Coding StandardINT01-C. Use rsize_t or size_t for all integer values representing the size of an objectPrior to 2018-01-12: CERT: Unspecified Relationship
ISO/IEC TR 24772:2013Unchecked Array Indexing [XYZ]Prior to 2018-01-12: CERT: Unspecified Relationship
ISO/IEC TS 17961:2013Tainted, potentially mutilated, or out-of-domain integer values are used in a restricted sink [taintsink]

Bibliography

[ISO/IEC 9899:2011]Annex J, J.2, "Undefined behavior" 
[Griffiths 2006] 
Prior to 2018-01-12: CERT: Unspecified Relationship
CWE 2.11CWE-7582017-06-29: CERT: Rule subset of CWE

CERT-CWE Mapping Notes

Key here for mapping notes

CWE-129 and ARR32-C

Intersection( CWE-188, EXP39-C) = Ø

ARR32-C addresses specifying the size of a variable-length array (VLA). CWE-129 addresses invalid array indices, not array sizes.

CWE-758 and ARR32-C

Independent( INT34-C, INT36-C, MSC37-C, FLP32-C, EXP33-C, EXP30-C, ERR34-C, ARR32-C)

CWE-758 = Union( ARR32-C, list) where list =


  • Undefined behavior that results from anything other than too large a VLA dimension.


CWE-119 and ARR32-C


  • Intersection( CWE-119, ARR32-C) = Ø



  • ARR32-C is not about providing a valid buffer but reading/writing outside it. It is about providing an invalid buffer, or one that exhausts the stack.


Bibliography

...


...

Image Modified Image Modified Image Modified