...
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <stdlib.h> #include <stdint.h> /* For SIZE_MAX */ 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; } |
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <stdlib.h> #include <stdint.h> 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; } |
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <stdlib.h> #include <stdint.h> 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 | ||||
|---|---|---|---|---|
| ||||
#include <stdlib.h> #include <limits.h> void *AllocBlocks(size_t cBlocks) { if (cBlocks == 0) { return NULL; } unsigned long long alloc = cBlocks * 16; return (alloc < UINT_MAX) ? malloc(cBlocks * 16) : NULL; } |
...
| Code Block | ||||
|---|---|---|---|---|
| ||||
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
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;
}
|
...