...
In the example mentioned below, the variable i will be instantiated with automatic storage duration within the block, but it’s never initialized. Thus, if the controlling expression has a non-zero value, the cause to printf will access an indeterminate value of i. Similarly, the call to function will also never get executed.
| Code Block | ||
|---|---|---|
| ||
| Warning | ||
int func ( int expr )
{
switch (expr) {
int i = 4;
f(i);
case 0:
i = 17;
/*falls through into default code */
default:
printf(“%d\nâ€, i);
}
return 0;
}
|
Compliant Solution
In the compliant solution, by moving the statements before the first case statement outside the switch block, the execution can be ensured and result in an expected behavior.
| Infocode | |||
|---|---|---|---|
| |||
| Wiki Markup |
int func ( int expr )
{
int i = 4; // Move the code outside the switch block
f(i); // Now the statements will get executed
switch (expr) { case 0: i = 17; /*falls through into default code */ default: printf(“%d\nâ€, i); } return 0; } |
Risk Assessment
Using test conditions or initializing variables inside the switch block before the first case statement, can result in unexpected behaviour as the above code will not be executed.
Recommendation | Severity | Likelihood | Remediation Cost | Priority | Level |
|---|---|---|---|---|---|
| Medium | unlikely | medium | P2 | L3 |