软件测试(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.

转载于:https://www.cnblogs.com/lmns/p/6474255.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值