Versions Compared

Key

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

...

Vulnerabilities that result from copying data to an undersized buffer often involve null-terminated character arrays (NTCA). Consult STR31-CPP. Guarantee that storage for character arrays has sufficient space for character data and the null terminator for specific examples of this rule that involve NTCA.

Noncompliant Code Example (Array)

Improper use of functions that limit copies with a size specifier, such as memcpy(), may result in a buffer overflow. In this noncompliant code example, an array of integers is copied from src to dest using memcpy(). However, the programmer mistakenly specified the amount to copy based on the size of src, which is stored in len, rather than the space available in dest. If len is greater than 256, then a buffer overflow will occur.

Code Block
bgColor#FFCCCC
enum { WORKSPACE_SIZE = 256 };

void func(const int src[], size_t len) {
  int dest[WORKSPACE_SIZE];
  memcpy(dest, src, len * sizeof(int));
  /* ... */
}

Compliant Solution (

...

Array)

The amount of data copied should be limited based on the available space in the destination buffer. This can be accomplished by adding a check to ensure the amount of data to be copied from src can fit in dest.

...