...
In this compliant solution, the print_array() function accepts a pointer to the structure and not rather than the structure itself.
| Code Block | ||
|---|---|---|
| ||
void print_array(struct flexArrayStruct *structP) {
size_t i;
puts("Array is: ");
for (i = 0; i < structP->num; i++) {
printf("%d", structP->data[i]);
}
puts("\n");
}
struct flexArrayStruct *structP;
size_t array_size;
size_t i;
/* initialize array_size */
/* space is allocated for the struct */
structP = (struct flexArrayStruct *)malloc(
sizeof(struct flexArrayStruct) + sizeof(int) * array_size
);
if (structP == NULL) {
/* Handle malloc failure */
}
structP->num = array_size;
for (i = 0; i < array_size; i++) {
structP->data[i] = i;
}
print_array(structP);
|
...
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
|---|---|---|---|---|---|
MEM33-C | low | unlikely | low | P3 | L3 |
Automated Detection
flexible array structs should not be:
- declared on the stack; they should be on the heap
- copied via assignment, they should be copied using memcpy() or some similar function
- passed as raw args to functions; pass a pointer to a flexarray struct intead.
ROSE can detect all of theseCompass/ROSE can detect some violations of this rule. In particular, it warns if the last element of a struct is an array with a small index (0 or 1).
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
...