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

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

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

#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*的表现c++

从这个实验里,发现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;
}

将以上局部变量存放在堆中则能够避免spa

相关文章
相关标签/搜索