-1

If, in a function, I have the following code:

someClass *x = new object(); x = nullptr;

is this a memory leak? Or, is the memory reallocated due to its local scope?

Thanks!

Not sure how to test this on my own.

zbrusko
  • 13
  • 3
  • 3
    Yes, this is explained in any [good c++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). See also [Must new always be followed by delete?](https://stackoverflow.com/questions/716353/must-new-always-be-followed-by-delete) – Jason Nov 04 '22 at 14:16
  • 2
    Whatever is `new`ed, must be `delete`d. – wohlstad Nov 04 '22 at 14:16
  • Note that this is not just a memory leak. Much worse things may generally happen because you are not properly destructing the constructed object. – Daniel Langr Nov 04 '22 at 14:22
  • That was what I thought, but I was having second thoughts if it happened in a function and wanted to be clear. Thank you! – zbrusko Nov 04 '22 at 14:24
  • just about everything in C++ happens "in a function" – Neil Butterworth Nov 04 '22 at 14:26
  • @DanielLangr, is that really true? The code is simply not destructing the object...there is no improper destruction going on. – MarkB Nov 04 '22 at 14:27
  • Classic memory leak in a nutshell. – Eljay Nov 04 '22 at 14:30
  • @MarkB There are many things that may go wrong when skipping destructor call. For instance, you may have buffered data in memory that won't be written into a file and you will end up with corrupted file content. – Daniel Langr Nov 04 '22 at 14:30
  • This all makes sense, I just had a brain cramp and a moment of doubt regarding the scope, and thought that there was dedicated memory space for functions that would all be marked for reallocation once a function goes out of scope. In this case, that applies to x, and not the new object, I presume. – zbrusko Nov 04 '22 at 14:35
  • @MarkB what if the class allocates resources, such as memory, file handles, sockets or whatever. not calling the destructor via delete leaks all those – Neil Butterworth Nov 04 '22 at 14:36
  • @zbrusko yes if you said Object x; the thing would be created on the stack, and the destructor would be called for you when the function exits. – Neil Butterworth Nov 04 '22 at 14:39
  • @zbrusko Pointers don't have destructors, so when they go out of scope **nothing happens**, – john Nov 04 '22 at 14:50

1 Answers1

0

This is a memory leak. It is about the clearest example as one can get.

stefaanv
  • 14,072
  • 2
  • 31
  • 53