我有以下代码.
#include <iostream>
int * foo()
{
int a = 5;
return &a;
}
int main()
{
int* p = foo();
std::cout << *p;
*p = 8;
std::cout << *p;
}
Run Code Online (Sandbox Code Playgroud)
而代码只是运行而没有运行时异常!
输出是 58
怎么会这样?本地变量的内存不能在其功能之外无法访问吗?
看下面的代码.我知道它不返回局部变量的地址,但为什么它仍然有效并将imain()中的变量赋值为'6'?如果从堆栈内存中删除变量,它如何仅返回值?
#include <iostream>
int& foo()
{
int i = 6;
std::cout << &i << std::endl; //Prints the address of i before return
return i;
}
int main()
{
int i = foo();
std::cout << i << std::endl; //Prints the value
std::cout << &i << std::endl; //Prints the address of i after return
}
Run Code Online (Sandbox Code Playgroud)