Versions Compared

Key

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

...

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

Code Block
bgColor#ccccff
langc
enum { BLOCK_HEADER_SIZE = 16 };

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

  if ((unsigned long long)length + BLOCK_HEADER_SIZE > 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;
}

...

In this noncompliant code example, the programmer attempts to prevent wrapping by allocating an unsigned long long integer called alloc and assigning it the result from cBlocks * 16.:

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

...

In this compliant solution, the cBlocks operand is upcast to unsigned long long, ensuring that the multiplication takes place in this size.:

Code Block
bgColor#ccccff
langc
static_assert(
  CHAR_BIT * sizeof(unsigned long long) >= 
  CHAR_BIT * sizeof(size_t) + 4, 
  "Unable to detect wrapping after multiplication"
);

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

...

Tool

Version

Checker

Description

Compass/ROSE

 

 

Can detect violations of this rule. It should look for patterns of (a op1 b) op2 c where:

    • c has a bigger type than a or b
    • Neither a nor b are typecast to c's type
    • op2 is assignment or comparison
Coverity6.5OVERFLOW_BEFORE_WIDENFully Implemented

Fortify SCA

5.0

 

Can detect violations of this rule with CERT C Rule Pack.

PRQA QA-C
Include Page
PRQA_V
PRQA_V

1890
1891
1892
1893
1894
1895
2790 (C)

Partially implemented.

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

...