int* alloc()
{
int* tmp = new int;
return tmp;
}
int main()
{
int* ptr = alloc();
......
......
delete ptr;
return 0;
}
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With