Versions Compared

Key

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

...

In this non-compliant code example, cBlocks is multiplied by 16 and the result is stored in the unsigned long long int alloc.

Code Block
bgColor#FFcccc
void* AllocBlocks(size_t cBlocks) {
  if (cBlocks == 0) return NULL;
  unsigned long long alloc = cBlocks * 16;
  return (alloc < UINT_MAX)
     ? malloc(cBlocks * 16)
     : NULL;
}

...

Upcasting only works when a size is represented using a smaller type. Because we recommend that all sizes be represented using size_t, upcasting is never a good idea. Instead, check to make sure the multiplication does not overflow using the methods described in INT32-C. Ensure that integer operations do not result in an overflow. In the following example, the multsize_t() function sets errno to a non-zero value if the multiplication operation results in an overflow.

Code Block
bgColor#ccccff
void *AllocBlocks(size_t cBlocks) {
  size_t alloc;

  if (cBlocks == 0) return NULL;
  alloc = multsize_t(cBlocks, 16);
  if (errno) {
    return NULL;
  }
  else {
    return malloc(alloc);
  }
} /* end AllocBlocks */

...