Versions Compared

Key

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

...

To ensure that 0 is never passed as a size argument to malloc(), size is checked to confirm it has a positive value.:

Code Block
bgColor#ccccff
langc
size_t size;

/* Initialize size, possibly by user-controlled input */

if (size == 0) {
  /* Handle error */
}
int *list = (int *)malloc(size);
if (list == NULL) {
  /* Handle allocation error */
}
/* Continue processing list */

...

This compliant solution does not pass a size argument of zero to the realloc() function.:

Code Block
bgColor#ccccff
langc
size_t nsize;
/* Initialize nsize */
char *p2;
char *p = (char *)malloc(100);
if (p == NULL) {
  /* Handle error */
}

/* ... */

p2 = NULL;
if (nsize != 0) {
  p2 = (char *)realloc(p, nsize);
}
if (p2 == NULL) {
  free(p);
  p = NULL;
  return NULL;
}
p = p2;

...

Tool

Version

Checker

Description

Compass/ROSE

 

 

Can detect some violations of this rule. In particular, it warns when the argument to malloc() is a variable that has not been compared against NULL or that is known at compile time to be 0.

Related Vulnerabilities

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

...