软件测试(Software Testing)HW1: The Problem which impress me most

  The problem which impress me most is that when a input file is not given as the rule, what would happen?

  Please look as the following code.

 1 #include <iostream>
 2 #include <cstdio>
 3 using namespace std;
 4 int main(){
 5     int t;
 6     scanf("%d", &t);
 7     while(t--){
 8         int num1, num2;
 9         scanf("%d%d", &num1, &num2);
10         printf("num1 = %d, num2 = %d, ans = %d\n", num1, num2, num1 + num2);
11     }
12     return 0;
13 }

  The code is expecting the input format like following input file.

1 4
2 1 1
3 2 3
4 4 6
5 2 8

  Of course the code1 can run correctly in input1. But what about input2?

1 4
2 1 1
3 2 3

  Here is the result.

  Why the case3 and case4 is same as the case2? This is due to the function call stack. Now we print the address of num1 and num2.

  We can see the address of the num1 and num2 didn’t change, but num1 and num2 are local variables, they die at the end of each time of the loop. Let’s have a look in the function call stack.

  Before num1 and num2 read case2, the stack is like step1, after they read case2, the stack like step2, then num1 and num2 die at the end of the loop, but the value of 0x...b0 and the value of 0x...b4 is still 3 and 2. When the loop is next time, the num1 and num2 are still at the same place. This time there is no value to read. So num1 and num2 use the garbage value in their address. So the result is the same as the case2.

  How to avoid this problem? I think we can check if we read at End of file. We change the scanf into the expression of while loop to fix this.

  Here is the code.

 1 #include <iostream>
 2 #include <cstdio>
 3 using namespace std;
 4 int main()
 5 {
 6     int t, num1, num2;
 7     scanf("%d", &t);
 8     while(t-- && ~scanf("%d%d", &num1, &num2)){
 9         printf("num1 = %d, num2 = %d, ans = %d\n", num1, num2, num1 + num2);
10     }
11     return 0;
12 }

  This can check eof. Let’s have a try.

  Now we fix this problem.

posted @ 2017-02-27 15:09  喷水小火龙  阅读(297)  评论(0编辑  收藏  举报