2

If I have a pointer that has already been used to create new[] memory. And then use it again without deleting the first on or setting it to nullptr, what happens exactly? Does the compiler deletes the first one on its own or does the memory become inaccessible?

Mureinik
  • 297,002
  • 52
  • 306
  • 350
Blackwolf23
  • 93
  • 1
  • 8
  • 2
    This may be of interest to you: [What is a smart pointer and when should I use one?](http://stackoverflow.com/questions/106508/what-is-a-smart-pointer-and-when-should-i-use-one?rq=1) – Benjamin Lindley May 19 '17 at 15:56
  • See here http://stackoverflow.com/questions/6500313/why-should-c-programmers-minimize-use-of-new for info on `operator new` and preferable alternatives – Steve Townsend May 19 '17 at 16:03
  • 1
    BTW, you might want to use tools like [valgrind](http://valgrind.org/) to detect such cases. – Kobi May 19 '17 at 16:31

2 Answers2

7

The previous buffer you allocated is stilled owned by your process, but is inaccessible (since you no longer track its pointer), and you have no way to free it. It will remain allocated until the program terminated. This is what's known as a memory leak.

Mureinik
  • 297,002
  • 52
  • 306
  • 350
2

The compiler doesn't do anything.
As you suspected, the memory becomes inaccessible (because you don't have its address anymore), but it is still reserved for your usage (meaning wasted).

Setting it to nullptr first does not help, you have to free it.

deviantfan
  • 11,268
  • 3
  • 32
  • 49