功能范围&递增参数
一个示例问题要求我们考虑下面的代码并预测函数 funct_1
将打印出什么内容:
void func_1(int i, int j) {
printf("i is %d, j is %d\n", i, j);
}
/* ... */
/* somewhere in the code, a call to func_1 */
int i = 30;
func_1(i, i++);
/* ... */
我认为当参数以这种递增的形式传递时,无法预测何时编译器会增加 i。然而,解决方案是:
The values in the argument are passed as an attack to the function, hence 'j' receives
a value '30' and then i receives the incremented value which is '31'.
Output: i is 31, j is 30
有人可以解释一下对功能的攻击是什么以及这是如何发生的吗?
A sample problem asks us to consider the code below and predict what will be printed out by the function funct_1
:
void func_1(int i, int j) {
printf("i is %d, j is %d\n", i, j);
}
/* ... */
/* somewhere in the code, a call to func_1 */
int i = 30;
func_1(i, i++);
/* ... */
I thought that when parameters are passed in this form where they are incremented, it is impossible to predict when the compiler would increment i. The solution, however, is:
The values in the argument are passed as an attack to the function, hence 'j' receives
a value '30' and then i receives the incremented value which is '31'.
Output: i is 31, j is 30
Could someone please explain what an attack to a function is and how this happens?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
预测并非不可能;编译器以确定性的方式工作,即使在规范未涵盖或未涵盖的灰色区域也是如此。使用这个特定的编译器参数被从右向左推送,并且后增量在右参数被推送后不久发生。
It is not impossible to predict; compilers work in a deterministic manner, even in the grey areas poorly covered or not covered by the specs. With this specific compiler arguments are pushed right to left, and the post-increment occurs shortly after the right parameter has been pushed.
一般来说,解决方案是错误的。你是对的;代码的行为是未定义的。在某些编译器上,答案可能是 30 和 31;对其他人来说,可能是 30 和 30;对其他人来说,可能是 31 和 31;其他人可能只是删除硬盘上的所有文件(因为未定义的行为是未定义的)。幸运的是,在编译器中,彻底清除所有问题痕迹的行为相对不太可能发生。
对于某些特定平台上的某些特定编译器,该解决方案可能是正确的。
实际上,我认为在
func_1()
中不可能为j
得到 31 - 但是产生 30 和 30 的操作序列是很容易想象的: < 的值code>i 被压入两次,然后 I 递增,然后调用该函数。The solution is wrong in general. You are correct; the behaviour of the code is undefined. On some compilers, the answer might be 30 and 31; on others, it might be 30 and 30; on others, it might be 31 and 31; and others might simply erase all the files on your hard drive (because undefined behaviour is undefined). Fortunately, the radical, remove-all-traces-of-the-trouble behaviour is relatively unlikely in a compiler.
For some specific compiler on some specific platform, the solution is probably correct.
Actually, I think that it is not possible to get 31 for
j
infunc_1()
- but an operation sequence that produces 30 and 30 is easily imaginable: the value ofi
is pushed twice, then I is incremented, then the function is called.