...
In this noncompliant code example, the dynamically allocated buffer referenced by p
overflows for values of n > INT_MAX
.:
Code Block | ||||
---|---|---|---|---|
| ||||
char *copy(size_t n, const char *str) { int i; char *p; if (n == 0) { /* Handle unreasonable object size error */ } p = (char *)malloc(n); if (p == NULL) { /* Handle malloc failure */ } for ( i = 0; i < n; ++i ) { p[i] = *str++; } return p; } /* ... */ char str[] = "hi there"; char *p = copy(sizeof(str), str); |
...
Declaring i
to be of type rsize_t
eliminates the possible integer overflow condition (in this example). Also, the argument n
is changed to be of type rsize_t
to document additional validation in the form of a check against RSIZE_MAX
.:
Code Block | ||||
---|---|---|---|---|
| ||||
char *copy(rsize_t n, const char *str) { rsize_t i; char *p; if (n == 0 || n > RSIZE_MAX) { /* Handle unreasonable object size error */ } p = (char *)malloc(n); if (p == NULL) { /* Handle malloc failure */ } for (i = 0; i < n; ++i) { p[i] = *str++; } return p; } /* ... */ char str[] = "hi there"; char *p = copy(sizeof(str), str); |
...
Tool | Version | Checker | Description | ||||||
---|---|---|---|---|---|---|---|---|---|
Compass/ROSE |
|
| Can detect violations of this recommendation. In particular, it catches comparisons and operations where one operand is of type | ||||||
Fortify SCA | 5.0 |
| Will detect integer operations that cause overflow but not all cases where | ||||||
| 93 S | Fully implemented. | |||||||
Splint |
|
|
|
...