b********r 发帖数: 1080 | 1 不是说不可以'返回一个指向临时变量的指针'么?
下面的例子在VC和g++下都正确执行了.
#include
using namespace std;
int* fun()
{
int f0=1;
int* f3=&f0;
return f3;
}
int main()
{
int* k=fun();
cout<<++(*k)<
return 0;
}
结果: 2. |
p***o 发帖数: 1252 | 2 so what? code should work under ANY circumstance
【在 b********r 的大作中提到】 : 不是说不可以'返回一个指向临时变量的指针'么? : 下面的例子在VC和g++下都正确执行了. : #include : using namespace std; : int* fun() : { : int f0=1; : int* f3=&f0; : return f3; : }
|
b********r 发帖数: 1080 | 3 我的理解是指针指向了函数中的临时变量.函数返回时,变量被自动消除.
这是指针指向的地址应该被释放了.所以结果至少应该是undefined.
我理解错了?
【在 p***o 的大作中提到】 : so what? code should work under ANY circumstance
|
t****t 发帖数: 6806 | 4 理解得很好, 但是你有没有理解undefined是什么意思呢?
【在 b********r 的大作中提到】 : 我的理解是指针指向了函数中的临时变量.函数返回时,变量被自动消除. : 这是指针指向的地址应该被释放了.所以结果至少应该是undefined. : 我理解错了?
|
s****t 发帖数: 698 | 5
undefine就是留给编译器自己去发挥,
但是很可能不受你控制。
【在 t****t 的大作中提到】 : 理解得很好, 但是你有没有理解undefined是什么意思呢?
|
w*********l 发帖数: 1337 | 6 不能算undefined吧?这种情况就算产生segmentation fault都算你幸运。很多的情况
下你是直接读写另一个变量了。C/C++是不会检查你读写的指针的语义的,能读就读,
能写就写。
【在 b********r 的大作中提到】 : 我的理解是指针指向了函数中的临时变量.函数返回时,变量被自动消除. : 这是指针指向的地址应该被释放了.所以结果至少应该是undefined. : 我理解错了?
|
l*****0 发帖数: 238 | 7 try this:
#include
using namespace std;
int* fun()
{
int f0=1;
int* f3=&f0;
return f3;
}
int fun0()
{
int ff[256];
memset(ff, 5, 1024);
return 0;
}
int main(int argc, _TCHAR* argv[])
{
int* k=fun();
fun0();
cout<<++(*k)<
return 0;
}
now the output becomes 84215146, which is 0x05050506
did you figure out anything?
your k points to a stack memory which hold whatever value happen to be there |
O*******d 发帖数: 20343 | 8 LZ should spend sometime to refresh on how stack work. |