简体   繁体   中英

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. Will tmp also be freed since ptr and tmp refer to the same location?

  2. If not then what happens to the pointer 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. Your function returns this address which, in main() , gets stored in the ptr variable. 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.

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:

#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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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