这不是应该产生段错误吗? 当我运行代码时,输出为 5。示例:http://ideone.com/gV2Nv
#include <iostream>
using std::cout;
using std::endl;
int* foo(int a) {
int b = a;
int* c = &b;
return c;
}
int main() {
int* a = foo(5);
cout << *a << endl;
return 0;
}
最佳答案
在函数中返回指向局部变量的指针是未定义的行为。
未定义行为不保证段错误。它仅意味着任何行为都是可能的,并且程序可以以任何方式运行。
一个常见的误解是,未定义行为意味着代码应该产生段错误,事实是,在代码调用未定义行为的情况下,标准并不要求任何特定行为,因此也没有要求名称。
C++ 标准第 1.3.24 节指出:
Permissible undefined behavior ranges from ignoring the situation completely with unpredictable results, to behaving during translation or program execution in a documented manner characteristic of the environment (with or without the issuance of a diagnostic message), to terminating a translation or execution (with the issuance of a diagnostic message).
关于c++ - 这个指针赋值应该产生段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10492513/