#include<iostream>
using namespace std;
int fn1()
{
int* p = new int(5);
return *p;
}
int main()
{
int a = fn1();
cout << "the value of a is:" << a;
return 0;
}
#include<iostream>
using namespace std;
int *fn1()
{
int* p = new int(5);
return p;
}
int main()
{
int *a = fn1();
cout << "the value of a is:" << a;
delete a;
return 0;
}
都是输出5,两个程序都在堆区开辟了一块内存空间,第一个程序返回局部变量指针指向的内容,导致了无指针指向了该块内存,出现了内存泄漏,第二个程序返回局部变量的指针,但是指针发生了拷贝,还是有指针指向堆区内存
第一个程序也能输出5,但是存在内存泄漏。