简体   繁体   English

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

[英]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;
}
  1. Here I have not freed tmp but ptr is freed explicitly. 在这里我没有释放tmp但是ptr被明确释放。 Will tmp also be freed since ptr and tmp refer to the same location? 由于ptr和tmp指向相同的位置,tmp是否也会被释放?

  2. If not then what happens to the pointer tmp? 如果不是那么指针tmp会发生什么? Does it cause a memory leak? 它会导致内存泄漏吗?

No, this does not cause a memory leak. 不,这不会导致内存泄漏。 Memory leaks are buffers (blocks of memory) that have been allocated but not returned (when they will no longer be used). 内存泄漏是已分配但未返回的缓冲区 (内存块)(当它们将不再使用时)。 In your alloc() function, tmp is not a buffer... it's a variable that, after the call to new , holds the address of a buffer. 在你的alloc()函数中, tmp不是一个缓冲区......它是一个变量,在调用new ,它保存缓冲区的地址 Your function returns this address which, in main() , gets stored in the ptr variable. 您的函数返回此地址,在main() ,该地址存储在ptr变量中。 When you later call delete ptr , you are releasing the buffer that ptr points to, thus the buffer has been released and there is no leak. 当你再打delete ptr ,你是释放缓冲区 ptr点,从而缓冲已被释放,也没有泄漏。

Your program will not cause a memory leak provided no uncaught exceptions are thrown . 如果没有抛出未捕获的异常,您的程序将不会导致内存泄漏。

You can do better and make it 100% bomb-proof like this: 你可以做得更好,让它像这样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;
}

Get into this habit early. 尽早养成这个习惯。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM