0

How does delete operator work in C++?

int *ptr = new int[2];
delete[] ptr;

How does delete operator know the amount of memory allocated, since ptr is just a int pointer and increment-ing(++) it would simply make it point to the next location in the continuously allocated structure.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • 1
    Your code has undefined behaviour. You meant `delete[] ptr`. – Lightness Races in Orbit Nov 02 '19 at 21:06
  • 1
    First of all, it should be `delete[]`. Second of all, it's the C++ compiler's and C++ library's job to know how much to delete, and is something that someone writing a C++ compiler has no reason to care about, at all. That's the C++ library's job. – Sam Varshavchik Nov 02 '19 at 21:07
  • 1
    Does this answer your question: [How does delete “know” the size of the operand array](https://stackoverflow.com/questions/197675/how-does-delete-know-the-size-of-the-operand-array)? Also, note that your code has Undefined Behaviour - you have to `delete[]` what you allocated with `new[]` and `delete` what you allocated with `new`. – Yksisarvinen Nov 02 '19 at 21:07
  • 1
    There is no delete operator in C. – eerorika Nov 02 '19 at 21:07
  • Thanks for your time everyone :) – Nephew of Stackoverflow Nov 02 '19 at 21:11
  • @SamVarshavchik C++ library's job..hmm. Could you please elaborate a bit? – Nephew of Stackoverflow Nov 02 '19 at 21:13
  • @Blastfurnace No, that mistake was tangential to the question, so fixing it was the right thing to do. There's a reason I pointed it out in the comments. – Lightness Races in Orbit Nov 02 '19 at 21:16
  • What's to "elaborate"? There's nothing to elaborate here. The C++ library knows how to do it, and that's all I need to know. In the ~30 years I've been coding C++, I don't recall a single time when I found the need to know the exact mechanical details of how this works. And even if I did, it would be just a simple matter of looking at the compiled code and see how a particular `delete[]` works. – Sam Varshavchik Nov 02 '19 at 21:17
  • @SamVarshavchik Sorry if I hurt you in any way but I was just curious enough – Nephew of Stackoverflow Nov 02 '19 at 21:18

1 Answers1

1

Allocators typically hide allocation information just before the pointer in question. The allocation includes that space, but the pointer is moved after it so you don't access/modify it. This is part of why writing to a pointer at a negative index breaks things so badly.

As noted in the comments, your code is broken as written, since you used delete ptr;, not delete[] ptr;; only the latter knows to look for the information needed to destruct the whole array, not just a single element.

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271