Versions Compared

Key

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

...

Noncompliant Code Example

This non compliant code example is noncompliant on systems where size_t is an unsigned 32-bit value and long long is a 64-bit value. In this example, the programmer tests for wrapping by comparing SIZE_MAX to length + BLOCK_HEADER_SIZE. Because length is declared as size_t, the addition is performed as a 32-bit operation and can result in wrapping. The comparison with SIZE_MAX in this example will always test false. If an wrapping occurs, malloc() will allocate insufficient space for mBlock, which can lead to a subsequent buffer overflow.

Code Block
bgColor#FFcccc
enum { BLOCK_HEADER_SIZE = 16 };

void *AllocateBlock(size_t length) {
  struct memBlock *mBlock;

  if (length + BLOCK_HEADER_SIZE > (unsigned long long)SIZE_MAX)
    return NULL;
  mBlock = (struct memBlock *)malloc(
    length + BLOCK_HEADER_SIZE
  );
  if (!mBlock) return NULL;

  /* fill in block header and return data portion */

  return mBlock;
}

GCC 3.4.4 produces a warning for this noncompliant code exampleSome compilers will diagnose this condition.

Compliant Solution (

...

Upcast)

In this compliant solution, the length operand is upcast to unsigned long long, ensuring that the addition takes place in this size.

...