...
This noncompliant code example attempts to declare a two-dimensional array of integers with variable length rows. On a platform with 64-bit integers, the loop will access memory outside the allocated memory section.
| Code Block | ||||
|---|---|---|---|---|
| ||||
/* assuming 32-bit pointer, 32-bit integer */
size_t i;
int **matrix = (int **)calloc(100, 4);
if (matrix == NULL) {
/* handle error */
}
for (i = 0; i < 100; i++) {
matrix[i] = (int *)calloc(i, 4);
if (matrix[i] == NULL) {
/* handle error */
}
}
|
...
This compliant solution replaces the hard-coded value 4 with sizeof(int *).
| Code Block | ||||
|---|---|---|---|---|
| ||||
size_t i;
int **matrix = (int **)calloc(100, sizeof(*matrix));
if (matrix == NULL) {
/* handle error */
}
for (i = 0; i < 100; i++) {
matrix[i] = (int *)calloc(i, sizeof(**matrix));
if (matrix[i] == NULL) {
/* handle error */
}
}
|
...