[英]Will this cause a memory leak in c++?
int* alloc()
{
int* tmp = new int;
return tmp;
}
int main()
{
int* ptr = alloc();
......
......
delete ptr;
return 0;
}
在这里我没有释放tmp但是ptr被明确释放。 由于ptr和tmp指向相同的位置,tmp是否也会被释放?
如果不是那么指针tmp会发生什么? 它会导致内存泄漏吗?
不,这不会导致内存泄漏。 内存泄漏是已分配但未返回的缓冲区 (内存块)(当它们将不再使用时)。 在你的alloc()
函数中, tmp
不是一个缓冲区......它是一个变量,在调用new
,它保存缓冲区的地址 。 您的函数返回此地址,在main()
,该地址存储在ptr
变量中。 当你再打delete ptr
,你是释放缓冲区 ptr
点,从而缓冲已被释放,也没有泄漏。
如果没有抛出未捕获的异常,您的程序将不会导致内存泄漏。
你可以做得更好,让它像这样100%防弹:
#include <memory>
std::unique_ptr<int> alloc()
{
std::unique_ptr<int> tmp { new int };
//... anything else you might want to do that might throw exceptions
return tmp;
}
int main()
{
std::unique_ptr<int> ptr = alloc();
// other stuff that may or may not throw exceptions
// even this will fail to cause a memory leak.
alloc();
alloc();
alloc();
auto another = alloc();
// note that delete is unnecessary because of the wonderful magic of RAII
return 0;
}
尽早养成这个习惯。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.