Versions Compared

Key

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

...

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

...

example.

...

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.

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

...