Note that there are some explanatory texts on larger screens.

plurals
  1. POHow does delete[] know it's an array?
    primarykey
    data
    text
    <p>Alright, I think we all agree that what happens with the following code is undefined, depending on what is passed,</p> <pre><code>void deleteForMe(int* pointer) { delete[] pointer; } </code></pre> <p>The pointer could be all sorts of different things, and so performing an unconditional <code>delete[]</code> on it is undefined. However, let's assume that we are indeed passing an array pointer,</p> <pre><code>int main() { int* arr = new int[5]; deleteForMe(arr); return 0; } </code></pre> <p>My question is, in this case where the pointer <strong>is</strong> an array, who is it that knows this? I mean, from the language/compiler's point of view, it has no idea whether or not <code>arr</code> is an array pointer versus a pointer to a single int. Heck, it doesn't even know whether <code>arr</code> was dynamically created. Yet, if I do the following instead,</p> <pre><code>int main() { int* num = new int(1); deleteForMe(num); return 0; } </code></pre> <p>The OS is smart enough to only delete one int and not go on some type of 'killing spree' by deleting the rest of the memory beyond that point (contrast that with <code>strlen</code> and a non-<code>\0</code>-terminated string -- it will keep going until it hits 0).</p> <p>So whose job is it to remember these things? Does the OS keep some type of record in the background? (I mean, I realise that I started this post by saying that what happens is undefined, but the fact is, the 'killing spree' scenario doesn't happen, so therefore in the practical world <em>someone</em> is remembering.)</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload