Versions Compared

Key

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

...

Compliant Solution (Rearrange Expression)

IIn In this compliant solution, length is subtracted from SIZE_MAX, ensuring that wrapping cannot occur, see INT30-C. Ensure that unsigned integer operations do not wrap.

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

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

  if (SIZE_MAX - length < BLOCK_HEADER_SIZE) return NULL;
  mBlock = (struct memBlock *)malloc(
    length + BLOCK_HEADER_SIZE
  );
  if (!mBlock) return NULL;
  /* fill in block header and return data portion */

  return mBlock;
}

...

Code Block
bgColor#ccccff
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;
}

...