The procedure given below is required to find and replace certain characters inside an input character string supplied in array . The characters to be replaced are supplied in array , while their respective replacement characters are supplied in array . Array has a fixed length of five characters, while arrays and contain three characters each. However, the procedure is flawed.
void find_and_replace (char *A, char *oldc, char *newc) {
for (int i=0; i<5; i++)
for (int j=0; j<3; j++)
if (A[i] == oldc[j])
A[i] = newc[j];
}
The procedure is tested with the following four test cases.
The tester now tests the program on all input strings of length five consisting of characters ‘’, ‘’, ‘’, ‘’ and ‘’ with duplicates allowed. If the tester carries out this testing with the four test cases given above, how many test cases will be able to capture the flaw?
View worked solution
Answer: B
The flaw in the find_and_replace procedure lies in the inner loop. When a character matches , it is immediately replaced by . However, the inner loop continues to run for subsequent indices . If the newly replaced character matches any (where ), it undergoes a second replacement in the same iteration of the outer loop (cascading replacement).
For a test case to capture this flaw, there must exist some indices and such that and . Let us analyze the four test cases:
-
- does not match or .
- does not match .
- No cascading occurs. (Flaw not captured)
-
- does not match or .
- does not match .
- No cascading occurs. (Flaw not captured)
-
- matches .
- If , it first becomes (at ) and then immediately becomes (at ). The correct output should have been . (Flaw captured)
-
- matches .
- If , it first becomes (at ) and then immediately becomes (at ). The correct output should have been . (Flaw captured)
Thus, only test cases 3 and 4 are able to capture the flaw.
Free practice · Your answers on this page are not saved.
