Versions Compared

Key

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

...

In this noncompliant code example, the dynamically allocated buffer referenced by p overflows for values of n > INT_MAX.:

Code Block
bgColor#FFcccc
langc
char *copy(size_t n, const char *str) {
  int i;
  char *p;

  if (n == 0) {
    /* Handle unreasonable object size error */
  }
  p = (char *)malloc(n);
  if (p == NULL) {
    /* Handle malloc failure */
  }
  for ( i = 0; i < n; ++i ) {
    p[i] = *str++;
  }
  return p;
}

/* ... */

char str[] = "hi there";
char *p = copy(sizeof(str), str);

...

Declaring i to be of type rsize_t eliminates the possible integer overflow condition (in this example). Also, the argument n is changed to be of type rsize_t to document additional validation in the form of a check against RSIZE_MAX.:

Code Block
bgColor#ccccff
langc
char *copy(rsize_t n, const char *str) {
  rsize_t i;
  char *p;

  if (n == 0 || n > RSIZE_MAX) {
    /* Handle unreasonable object size error */
  }
  p = (char *)malloc(n);
  if (p == NULL) {
    /* Handle malloc failure */
  }
  for (i = 0; i < n; ++i) {
    p[i] = *str++;
  }
  return p;
}

/* ... */

char str[] = "hi there";
char *p = copy(sizeof(str), str);

...

Tool

Version

Checker

Description

Compass/ROSE

 

 

Can detect violations of this recommendation. In particular, it catches comparisons and operations where one operand is of type size_t or rsize_t and the other is not.

Fortify SCA

5.0

 

Will detect integer operations that cause overflow but not all cases where size_t is not used.

LDRA tool suite

Include Page
LDRA_V
LDRA_V

93 S

Fully implemented.

Splint

Include Page
Splint_V
Splint_V

 

 

...