可能重复:
返回本地或临时变量的地址
add函数执行错误.它应该返回一个值而不是一个指针.当打印ans和*ans_ptr并且程序甚至给出正确的结果时,为什么没有任何错误?我猜z的变量已经超出范围,应该存在分段错误.
#include <stdio.h>
int * add(int x, int y) {
int z = x + y;
int *ans_ptr = &z;
return ans_ptr;
}
int main() {
int ans = *(add(1, 2));
int *ans_ptr = add(1, 2);
printf("%d\n", *ans_ptr);
printf("%d\n", ans);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它"有效"的原因是因为你很幸运.返回指向局部变量的指针是Undefined Behavior !! 你不应该这样做.
int * add(int x, int y) {
int z = x + y; //z is a local variable in this stack frame
int *ans_ptr = &z; // ans_ptr points to z
return ans_ptr;
}
// at return of function, z is destroyed, so what does ans_ptr point to? No one knows. UB results
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
991 次 |
| 最近记录: |