Rules / C/C++
SHIELD-CPP-011
Integer overflow in malloc size
What it detects
malloc with a multiplied size can overflow and allocate too little memory.
How to fix
Use calloc or check for multiplication overflow before allocating.
Vulnerable — Shield flags thisimage_alloc.c
#include <stdlib.h>
#include <stdint.h>
uint8_t *alloc_pixels(size_t width, size_t height) {
/* width * height can overflow, allocating a tiny buffer */
uint8_t *buf = malloc(width * height);
if (buf == NULL)
return NULL;
return buf;
}
Fixed — scans cleanimage_alloc.c
#include <stdlib.h>
#include <stdint.h>
uint8_t *alloc_pixels(size_t width, size_t height) {
/* calloc checks the multiplication for overflow internally */
uint8_t *buf = calloc(width, height);
if (buf == NULL)
return NULL;
return buf;
}
Both snippets are verified against the shipped scanner: the vulnerable one triggers SHIELD-CPP-011, the fixed one does not.