...
Code Block | ||||
---|---|---|---|---|
| ||||
const char *table[] = { "black", "white", "blue", "green" };
const char *set_background_color(void) {
int color_index;
GET_TAINTED_INTEGER(int, color_index);
const char *color = table[color_index]; /* violation */
/* ... */
return color;
} |
Compliant Solution
This compliant solution defines the acceptable range for color_index
as [1, MAX_COLOR_INDEX]
.
Code Block | ||||
---|---|---|---|---|
| ||||
enum { MAX_COLOR_INDEX = 3 };
const char *table[] = { "black", "white", "blue", "green" };
const char *set_background_color(void) {
int color_index;
GET_TAINTED_INTEGER(int, color_index);
if (color_index < 0 || colo_index > MAX_COLOR_INDEX)
return NULL; /* indicate error to caller */
const char *color = table[color_index];
/* ... */
return color;
} |
The test for length == 0
ensures that a nonzero number of bytes is allocated. (See MEM04-C. Do not perform zero-length allocations.)
...