Versions Compared

Key

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

...

If both size_t and unsigned long long types are represented as a 64-bit unsigned value, the result of the multiplication operation may not be representable as an unsigned long long value.

Compliant Solution

...

1a

Wiki Markup
Make sure that integer values passed as size arguments to memory allocation functions are valid and have not been corrupted due to integer overflow, truncation, or sign error \[[Integers (INT)|04. Integers (INT)]\]. In the following example, the {{multsize_t()}} function multiples two values of type {{size_t}} and sets {{errno}} to a non-zero value if the resulting value cannot be represented as a {{size_t}} or to zero if it was representable.

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 */

Compliant Solution 1b

Alternately, since multsize_t() is not available on all platforms, you may wish to use a more portable solution. You can check for invalid cBlocks values (zero or too much) as follows:

Code Block
bgColor#ccccff

enum { BLOCKSIZE = 16 };
... 
void *AllocBlocks(size_t cBlocks) {
  size_t alloc;

  if (cBlocks == 0 || cBlocks > SIZE_MAX / BLOCKSIZE) return NULL;
  return malloc (cBlocks * BLOCKSIZE);
} /* end AllocBlocks */

In either case, note that we have left the handling of allocation errors as an exercise for the reader.

Non-Compliant Code Example 2

...

Wiki Markup
\[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] Section 7.20.3, "Memory Management Functions"
\[[Seacord 05|AA. C References#Seacord 05]\] Chapter 4, "Dynamic Memory Management," and Chapter 5, "Integer Security"
\[Coverity 07\|AA. C References#Coverity 07\]