Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are memory leaks possible with decltype(new any_type())?

I am checking for any memory leaks possibility with class pointers using valgrind and found out that following program has no memory leaks :

#include <iostream>
#include <utility>
#include <memory>

using namespace std;

class base{};

int main()
{
  unique_ptr<base> b1 = make_unique<base>();
  base *b2 = new base();
  cout << is_same<decltype(new base()), decltype(b1)>::value << endl;
  cout << is_same<decltype(new base()), decltype(b2)>::value << endl;
  delete b2;
  return 0;
}

How can this be possible?

like image 927
0x6773 Avatar asked May 18 '15 13:05

0x6773


People also ask

When can you tell that a memory leak will occur?

In computer science, a memory leak is a type of resource leak that occurs when a computer program incorrectly manages memory allocations in such a way that memory which is no longer needed is not released. A memory leak may also happen when an object is stored in memory but cannot be accessed by the running code.

Are memory leaks permanent?

Physical or permanent damage does not happen from memory leaks. Memory leaks are strictly a software issue, causing performance to slow down among applications within a given system. It should be noted a program taking up a lot of RAM space is not an indicator that memory is leaking.

Can you have a memory leak without malloc?

Is it possible to make memory leak without using malloc? ... is: Yes, it is possible.

Which condition causes memory leak?

Memory leaks are a common error in programming, especially when using languages that have no built in automatic garbage collection, such as C and C++. Typically, a memory leak occurs because dynamically allocated memory has become unreachable.


1 Answers

The operand of decltype (and also sizeof) is not evaluated, so any side-effects, including memory allocation, won't happen. Only the type is determined, at compile-time.

So the only memory allocations here are in make_unique and the first new base(). The former is deallocated by the unique_ptr destructor, the latter by delete b2, leaving no leaks.

like image 187
Mike Seymour Avatar answered Sep 17 '22 15:09

Mike Seymour