Versions Compared

Key

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

...

In this noncompliant example, the user-defined function get_size() (not shown) is used to calculate the size requirements for a dynamic array of long int that is assigned to the variable num_elements. When calloc() is called to allocate the buffer, num_elements is multiplied by sizeof(long) to compute the overall size requirements. If the number of elements multiplied by the size cannot be represented as a size_t, then calloc() may allocate a buffer of insufficient size. When data is copied to that buffer, an overflow may occur.

Code Block
bgColor#FFCCCC
langc
size_t num_elements;

long *buffer = (long *)calloc(num_elements, sizeof(long));
if (buffer == NULL) {
  /* Handle error condition */
}
/*...*/
free(buffer);
buffer = NULL; 

...

In this compliant solution, the the two arguments num_elements and sizeof(long) are checked before the call to calloc() to determine if wrapping will occur.

Code Block
bgColor#ccccff
langc
long *buffer;
size_t num_elements;

if (num_elements > SIZE_MAX/sizeof(long)) {
  /* Handle error condition */
}
buffer = (long *)calloc(num_elements, sizeof(long));
if (buffer == NULL) {
  /* Handle error condition */
}

...