C++局部指针返回的危险 char*返回用strdup处理

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

非字符串类型数据

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;
} 

字符串和char*的表现

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

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

char*与上个例子的变量一样,出来就没了。 所以在返回char*时候,一般加strdup(char*) 该函数类似将c++中的new 将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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值