Versions Compared

Key

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

...

Code Block
bgColor#FFcccc
enum { BLOCKSIZEBLOCK_HEADER_SIZE = 16 };
unsigned long long max = UINT_MAX;

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

  if (length + BLOCK_HEADER_SIZE > max) return NULL;
  mBlock = malloc(length + BLOCK_HEADER_SIZE);
  if (!mBlock) return NULL;

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

  return mBlock;
}

...

Code Block
bgColor#ccccff
enum { BLOCKSIZEBLOCK_HEADER_SIZE = 16 };
unsigned long long max = UINT_MAX;

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

  if ((unsigned long long)length + BLOCK_HEADER_SIZE > max) return NULL;
  mBlock = malloc(length + BLOCK_HEADER_SIZE);
  if (!mBlock) return NULL;

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

  return mBlock;
}

...

In this non-compliant code example, the programmer attempts to prevent integer overflow by allocating an unsigned long long integer called alloc and assigning it the result from cBlocks * 16.

Code Block
bgColor#FFcccc

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

...