Detect Overflows in Buffer Size Computation
If you are computing the size of a buffer from unsigned integers, for the Overflow mode for unsigned integer option, instead of the default value allow, use forbid. Using this option helps you detect an overflow at the buffer computation stage. Otherwise, you might see an error later due to insufficient buffer. This option is available on the Check Behavior node under
Code Prover Verification in the Configuration pane.
For this example, save the following C code in a file display.c:
#include <stdlib.h>
#include <stdio.h>
int get_value(void);
void display(unsigned int num_items) {
int *array;
array = (int *) malloc(num_items * sizeof(int)); // overflow error
if (array) {
for (unsigned int ctr = 0; ctr < num_items; ctr++) {
array[ctr] = get_value();
}
for (unsigned int ctr = 0; ctr < num_items; ctr++) {
printf("Value is %d.\n", ctr, array[ctr]);
}
free(array);
}
}
void main() {
display(33000);
}Start a Polyspace® Code Prover™ analysis using this command:
This command starts a Polyspace Code Prover analysis assuming apolyspace-code-prover -sources display.c -target c-167
c-167target. This target uses 16-bit integers.After the analysis ends, open the results.
Polyspace detects an orange Illegally dereferenced pointer error on the line
array[ctr] = get_value()and a red Non-terminating loop error on theforloop.This error follows from an earlier error. For a 16-bit
int, there is an overflow on the computationnum_items * sizeof(int). Polyspace does not detect the overflow because it occurs in computation withunsignedintegers. Instead Polyspace wraps the result of the computation causing the Illegally dereferenced pointer error later.Change the value of the option Overflow mode for unsigned integer to
forbidand run a second analysis:Polyspace detects a red Overflow error in the computationpolyspace-code-prover -sources display.c -target c-167 -unsigned-integer-overflows forbid
num_items * sizeof(int).