C 指针的常见题 函数传参时的内存泄露


#include <iostream>

using namespace std;

void test(int* p)//void test(int* &p)
{
cout<<"In the function;from main"<<endl;

cout<<"Where is the p"<<endl;
cout<<&p<<endl;

cout<<"What's the p point to"<<endl;
cout<<p<<endl;

cout<<"p=new int[10]"<<endl;
cout<<"What's the p point to now"<<endl;
p=new int[10];
cout<<p<<endl;

cout<<"And the location of p is unchanged"<<endl;
cout<<&p<<endl;
cout<<"Out of the function ;return to main"<<endl;


}

int main()
{
int *p=NULL;
cout<<"Where is the p"<<endl;
cout<<&p<<endl;

cout<<"What's the p point to"<<endl;
cout<<p<<endl;

test(p);

cout<<"What's the p point to now"<<endl;
cout<<p<<endl;

return 0;
}





Where is the p
0012FF28
What's the p point to
00000000
In the function;from main
Where is the p
0012FE54
What's the p point to
00000000
p=new int[10]
What's the p point to now
001E1AD0
And the location of p is unchanged
0012FE54
Out of the function ;return to main
What's the p point to now
00000000
请按任意键继续. . .


小结:
指针归根到底也是一个值,存放在栈中,有他自己的位置,他的值是指向内存的地址的。
就像这段代码,函数test的形参一开始指向的内存地址是main函数中p指向的地址。
至此,main函数中的p在test函数中没什么作用了,而test函数的作用仅仅是为形参p开辟空间,造成内存泄露。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值