NShiftKey-Rule-Guide logo NShiftKey-Rule-Guide

1. Vulnerability Description

2. Vulnerability Countermeasure

3. Sample Code

#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;
}
#include <stdlib.h>
#include <stdint.h>
 
 
enum { BLOCK_HEADER_SIZE = 16 };
  
void *AllocateBlock(size_t length) {
  struct memBlock *mBlock;
 
  // Avoid overflowing through the upcast.
  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;
}