这会导致c++中的内存泄漏吗?

Will this cause a memory leak in c++?

本文关键字:内存 泄漏 c++      更新时间:2023-10-16
int* alloc()
{
    int* tmp = new int;
    return tmp;
}
int main()
{
    int* ptr = alloc();
    ......
    ......
    delete ptr;
    return 0;
}
  1. 这里我没有释放tmp,但是显式释放了ptr。tmp也会吗?被释放,因为PTR和TMP指的是同一位置?

  2. 如果不是,那么指针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;
}

早点养成这个习惯。