1146
Example Language: JavaScript (Good)
let step = input1 + input2;
switch(step) {
case 1:
alert("Process step 1.");
break;
case 2:
alert("Process step 2.");
break;
case 3:
alert("Process step 3.");
break;
default:
alert("Unexpected step encountered.");
}
// program execution continues...
Example 5:
The Finite State Machine (FSM) shown in the "bad" code snippet below assigns the output ("out")
based on the value of state, which is determined based on the user provided input ("user_input").
Example Language: Verilog (Bad)
module fsm_1(out, user_input, clk, rst_n);
input [2:0] user_input;
input clk, rst_n;
output reg [2:0] out;
reg [1:0] state;
always @ (posedge clk or negedge rst_n )
begin
if (!rst_n)
state = 3'h0;
else
case (user_input)
3'h0:
3'h1:
3'h2:
3'h3: state = 2'h3;
3'h4: state = 2'h2;
3'h5: state = 2'h1;
endcase
end
out <= {1'h1, state};
endmodule
The case statement does not include a default to handle the scenario when the user provides
inputs of 3'h6 and 3'h7. Those inputs push the system to an undefined state and might cause a
crash (denial of service) or any other unanticipated outcome.
Adding a default statement to handle undefined inputs mitigates this issue. This is shown in the
"Good" code snippet below. The default statement is in bold.
Example Language: Verilog (Good)
case (user_input)
3'h0:
3'h1:
3'h2:
3'h3: state = 2'h3;
3'h4: state = 2'h2;
3'h5: state = 2'h1;
default: state = 2'h0;
endcase
CWE Version 4.14
CWE-479: Signal Handler Use of a Non-reentrant Function
CWE-479: Signal Handler Use of a Non-reentrant Function