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?
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.
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.
Is it possible to make memory leak without using malloc? ... is: Yes, it is possible.
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.
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.
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