-2

When we deallocate the heap memory occupied by an array, I have a little confusion regarding the syntax

int *p = new int[5];

Now for deallocating, which one is correct from the following:

delete p;

OR

delete[ ] p;

The latter seems to be more correct. But it confuses me, I don't understand that how would it know that how much memory the array exists on. I mean, we are only giving it the starting address of the array(through p). So, beginning from the starting address how will the compiler know that till where does it have to deallocate, and when to stop the deallocation.

amm98d
  • 1,997
  • 2
  • 9
  • 15

2 Answers2

1

Your second syntax is correct, and the compiler knows the size of the array since it took note of it when you allocated the array.This is usually stored in a piece of memory just before the memory that you allocated for the array. That way when it's time to free the memory, the deallocator knows exactly how much memory to free, by checking this memory.

Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88
  • So, even if I have made multiple heap arrays, the compiler knows about the size of each & I shouldn't worry about it when deallocating, right? – amm98d Jan 30 '18 at 16:15
  • Yup, that is completely correct. – Arnav Borborah Jan 30 '18 at 16:16
  • the interesting question is why the different syntax is needed. If the compiler can remember that this is an array of n members, why cant it remember that this was a scalar vs an array `new` – pm100 Jan 30 '18 at 16:19
  • @pm100 If you get the pointer through a library, the compiler doesn't know that it was created using `new[]`. Checking that at run time is a cost, and C++'s mantra is "don't pay for what you don't use". :) – Rakete1111 Jan 30 '18 at 16:42
0

In the below statement you are creating memory dynamically for int array of 5 integer

int *p = new int[5]; 

Its looks like below

 p = operator new [] (20); /** p points to first 20 bytes from starting address **/

To free or de-allocating p you should use

delete [] p;

It's looks like below

operator delete [] (p); /* It free frees memory of 20 bytes from where p is pointing */

Note : if you using only delete p then it won't free whole 20 bytes. delete p internally converts as operator delete (p);

Achal
  • 11,821
  • 2
  • 15
  • 37