Versions Compared

Key

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

...

Code Block
size_t num_elements = get_size();
long *buffer = calloc(num_elements, sizeof(long));
if (buffer == NULL) {
  /* handle error condition */
}

Compliant Solution 1

To correct this, a test is performed on the product of num_elements and sizeof(long) before the call to calloc(). The test valides that the multiplication performed by calloc() and can be performed successfully. The comparison checks the product against the system defined limit for size_t 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_MAXIt is assumed in the following example that the call to multsize_t() does not return if the multiplication operation results in an overflow and that, if the function returns succesfully, the multiplication performed by calloc() and can also be performed successfully.

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

Note that the maximum amount of allocatable memory is typically limited to a value less than SIZE_MAX (the maximum value of size_t).

References