C++基础--指针---返回指针时栈被移除的坑

1.函数局部变量地址释放的坑

main()调用test()方法,返回a的地址,但是a是test()的局部变量,因此在test()调用结束之后,test()的栈空间就被移除,a的储存空间被释放,即使保存了指向a的指针,也无法获得10. 第一次能得到10的原因是编译器优化保留了一次数据。

#include <iostream>
using namespace std;
int* test();

int main(){
	int *p = test();
	cout<< *p <<endl;
	cout<< *p <<endl;
	

	//答案是10  0 

}

int* test(){
	int a = 10;
	return &a;
} 

2.字符串和char*的表现

从这个实验里,发现string的地址是没有变化的,即使函数执行完毕,也能获得正确的值。

解释:字符串是存在静态区内的而非函数栈内,消亡的方式与普通变量不一样,所以依旧可以正确获取其值

​ char*与上个例子的变量一样,出来就没了。

#include <iostream>
#include <string>

using namespace std;
string test();
char* test1();
int* test2();
int main() {
	string p = test();
	cout << "变量string的地址" << &p << endl;
	cout << p << endl;
	cout << p << endl;
	char* p1 = test1();
	printf("变量char数组的地址%p\n", p1);
	cout << "char数组的值" << *p1 << endl;
	cout << "char数组的值" << *p1<< endl;

	/**
	结果是
	变量string在函数里的地址0x6ffe00
	变量string的地址0x6ffe00
	helloworld
	helloworld
	变量char在函数中的地址00000000006ffdc0
	变量char数组的地址00000000006ffdc0
	char数组的值  
	char数组的值
	**/
}

string test() {
	string a = "helloworld";
	cout << "变量string在函数里的地址\n" << &a << endl;
	return a;
}


char* test1() {
	char a[] = { 'h','h','h' };
	printf("char数组在函数中的地址%p\n", a);
	return a;
}

将以上局部变量存放在堆中则可以避免

posted @ 2020-12-04 14:20  lsxkugou  阅读(205)  评论(0编辑  收藏  举报