...
Any variable that is used to represent the size of an object including, but not limited to, integer values used as sizes, indices, loop counters, and lengths should be declared as size_t
.
Non-Compliant Code Example
In this example, the dynamically allocated buffer referenced by p will overflow for values of n > INT_MAX
.
Code Block |
---|
char *copy(size_t n, char *str) {
int i;
char *p = malloc(n);
for ( i = 0; i < n; ++i ) {
p[i] = *str++;
}
return p;
}
char *p = copy(20, "hi there");
|
Compliant Solution
Declaring i to be of type size_t
eliminates the possible integer overflow condition.
Code Block |
---|
char *copy(size_t n, char *str) {
size_t i;
char *p = malloc(n);
for ( i = 0; i < n; ++i ) {
p[i] = *str++;
}
return p;
}
char *p = copy(20, "hi there");
|
Non-Compliant Code Example
The user defined function calc_size
(not shown) is used to calculate the size of the string other_string
. The result of calc_size
is a signed int
returned into str_size
. Given that there is no check on str_size
, it is impossible to tell whether the result of calc_size
is an appropriate parameter for malloc, that is, a positive integer that can be properly represented by a signed int
type.
Code Block |
---|
int str_size = calc_size(other_string);
char *str_copy = malloc(str_size);
|
Compliant Solution
By changing str_size
to a variable of type size_t
, it can be ensured that the call to malloc()
is, at the least, supplied a non-negative number.
...
Include Page |
---|
| c:INT01 NCCE 1 |
---|
| c:INT01 NCCE 1 |
---|
|
Include Page |
---|
| c:INT01 NCCE 2 |
---|
| c:INT01 NCCE 2 |
---|
|
...
Non-Compliant Code Example
Add an example using size_t as an index
...