Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 336
kishore Avatar asked May 10 '14 11:05

kishore


2 Answers

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.

like image 119
mah Avatar answered Sep 28 '22 15:09

mah


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.

like image 21
Richard Hodges Avatar answered Sep 28 '22 15:09

Richard Hodges