C++之局部变量(栈区)
局部变量存放在栈区,栈区开辟的数据由编译器自动释放
局部变量的作用域只在此函数中,此函数运行返回后,编译器会自动释放局部变量。
当函数返回局部变量的值时,程序不会出错,因为返回的结果是一个值的拷贝,不涉及地址。
但当函数返回局部变量的地址或引用时,运行结果会出错。因为函数只是把指针或引用复制后返回了,而他们指向的内存中的数据已经被释放了。
一、返回局部变量的值
#include<iostream> using namespace std; int func() { int a = 10; return a; } int main() { int b = func(); cout << b << endl; cout << b << endl; cout << b << endl; return 0; }
运行结果:成功返回
10 10 10 -------------------------------- Process exited after 0.9071 seconds with return value 0 请按任意键继续. . .
二、返回局部变量的地址:(错误)
#include<iostream> using namespace std; int * func() { int a = 10; return &a; } int main() { int *p = func(); cout << *p << endl; //第一次正常返回,因为编译器操碎了心,给数据做了一个保留 cout << *p << endl; //第二次结果错误,因为a的内存已经释放 cout << *p << endl; //结果仍然错误 return 0; }
运行结果:错误
10 0 0 -------------------------------- Process exited after 1.004 seconds with return value 0 请按任意键继续. . .
三、返回局部变量的引用:(错误)
#include<iostream> using namespace std; int& func() { int a = 10; return a; } int main() { int &y = func(); cout << y << endl; //结果正确,编译器对结果做了保留 cout << y << endl; //结果错误,因为a的内存已经释放 cout << y << endl; //结果错误 return 0; }
运行结果:错误
10 0 0 -------------------------------- Process exited after 4.366 seconds with return value 0 请按任意键继续. . .
下一篇:
解决javac命令错误的问题