0

This will lead to memory leak:

int var = *new int(5);

This will not (if later freed):

int* var = new int(5); 

Question: Will this lead to memory leak?

int& var = *new int(5);

Yes, I should use smart pointers instead but that is not the question :)

Viktor Skarve
  • 129
  • 1
  • 8
  • 4
    "should use smart pointers" ? really? I think you should just use `int var = 5;` – 463035818_is_not_an_ai Feb 04 '21 at 09:21
  • 2
    If you create something with "new" and don't destroy it with "delete", you have a leak. – molbdnilo Feb 04 '21 at 09:22
  • Yes (@largest_prime_is_463035818), that is true. However this is just an exempel (not a practical one) and is more to understand how the language works (if it will lead to memory leak or not) so that I know how to use pointers when they are the only alternative, if that is ever going to happen to me. – Viktor Skarve Feb 04 '21 at 09:27
  • 1
    _Will this lead to memory leak?_ Not necessarily; you need to take into account the [_as-if rule_](https://stackoverflow.com/q/15718262/580083). Live demo: https://godbolt.org/z/xxGf43. – Daniel Langr Feb 04 '21 at 09:39
  • @DanielLangr that's correct. Heap-allocation elision is a relatively new thing with compilers tho. See https://godbolt.org/z/bn7rTj – Aykhan Hagverdili Feb 04 '21 at 09:53
  • @AyxanHaqverdili Depends on a compiler. Clang elides these allocations since version 4 (on Godbolt). – Daniel Langr Feb 04 '21 at 09:55

3 Answers3

2

It will cause a memory leak. What your doing there is allocating a block of memory, dereferencing the pointer and assigning it to the variable var. Dynamic memory allocation does not deallocate itself when gone out of the scope, instead the variable var will be destroyed, not the pointer that you allocated.

To delete it, what you need to do is something like this,

int& var = *new int(5);
delete &var;
D-RAJ
  • 3,263
  • 2
  • 6
  • 24
0

Yes it will. I tested it in Visual studio and it does. Wherever you use new and don't have delete, you have a memory leak. You allocate a dynamic memory but never free it.

enter image description here

Silidrone
  • 1,471
  • 4
  • 20
  • 35
0

Yes it will leak. As already comment there have to be a delete to every new. There should be a warning on the assignment to the reference &var of a then anonym heap variable int(5) for which is no proper handle available anymore. Deleting as proposed in the other answer a reference is against the idea of a reference. The most important difference between reference and pointers is the benefit to expect that the reference always has a target, while one has to expect that a pointer is dangling or zero and to act like so. Additionally there is the paradigm, that one does not own a reference once it is passed over, so delete is the very last one should do with it.

Patrick Z
  • 194
  • 9