classc
{
public:
int*p;
};
voidf(int*p,int*t=NULL){//但是将函数参数改变之后输出就变成0
p=newint[10];
t=p;
delete[]p;
}
intmain(){
cb;
int*t;
f(b.p,t);
t=newint[10];
t[1]=10086;
cout[usedforc.p],secondblock--->[free]
释放后
c.p==fistblock---->[allfree]
第二次分配
t=fistblock---->[usedfort],secondblock--->[free]
这样c.p==t==fistblock--->都指向为t分配的内存了;
因为函数f的参数c是引用,所以f::c.p=main::c.p
所以函数f调用后,main::c.p指向已经释放的内存,而这块内存,
很大程度上(注意不是必然的),
可能又被分配给t了,
此时自然就有c.p==t了;
c.p[1]根本就是t[1];
只是现在c.p是野指针,c.p[1]根本就是野指针的非法使用,
所以某些时候,运行出错,也是可能的.
所以,这是很大几率的一种巧合,而不是必然
|