Versions Compared

Key

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

...

Code Block
size_t num_elements = get_size();
unsigned long long *buffer = calloc(num_elements, sizeof(unsigned long long));

Compliant Solution 1

To correct this, a test is performed on the product of num_elements and sizeof(long) post the call to calloc(). The test reproduces the multiplication performed by calloc() and evaluates the product to determine if an overflow occured. The comparison checks the product against the system defined limit on a size_t data type ISO/IEC 9899 shifted left by one against the product of num_elements and sizeof(long). if the product's highest bit is set, then it is assumed that an arithmetic overflow has occured. Although this limits the amount of memory that can be allocated, it is important to note that typically, the maximum amount of allocatable memory is limited to a value less than SIZE_MAX.

Code Block
size_t num_elements = calc_size();
long *buffer = NULL calloc(num_elements, sizeof(long));
if ((num_elements*sizeof(long)) >= (SIZE_MAX>>1)) {
   long /*buffer = calloc(num_elements, sizeof(long));Handle error condition*/
}
else {
/* Handle error condition */
}

...