-2 c
#include <stdio.h>
int ?addition(int a, int b){
int c = a + b ;
int ?d = &c ;
return d ;
}
int main (void) {
int result = ?(addition(1, 2));
int ?resultptr = addition(1, 2);
printf(”result = %d\n”, ?resultptr);
printf(”result = %d\n”, result);
return 0 ;
}
Run Code Online (Sandbox Code Playgroud)
这将给出正确的答案.但奇怪的是,一旦我互换了最后两个printf()的顺序,就会给出异常的答案.
printf(”result = %d\n”, result);
printf(”result = %d\n”, ?resultptr);
Run Code Online (Sandbox Code Playgroud)
这是为什么?是因为printf()的一些内部实现?
我打开了-Wall选项,但没有显示警告.
谢谢您的回答!这是我在stackoverflow上的第一个问题.
但为什么反转顺序会给出不同的答案?如果是由于返回局部变量的未定义行为,为什么第一个程序给出正确答案但第二个程序不能,而唯一的区别是printf()的顺序?
在这个功能中,
int ?addition(int a, int b){
int c = a + b ; // Object on the stack
int ?d = &c ; // d points to an object on the stack.
return d ;
}
Run Code Online (Sandbox Code Playgroud)
您正在从堆栈返回指向对象的指针.从函数返回后返回的内存无效.访问该内存会导致未定义的行为.
如果你改变函数返回一个int,那就没事了.
int addition(int a, int b){
return (a + b);
}
int main (void) {
int result1 = addition(1, 2);
int result2 = addition(2, 3);
printf(”result = %d\n”, result1);
printf(”result = %d\n”, result2);
return 0 ;
}
Run Code Online (Sandbox Code Playgroud)