views:

83

answers:

4

I am not sure if both of these works to delete:

p = new int[1];

delete p

and

delete [] p;

If both work, what is the difference between the above two deletes?

+1  A: 

delete p deletes only one element. delete [] p deletes an array. If you use new type[], then use delete [].

If you're new has a [], then delete has a [].

Btw there has to be an exact dup of this somewhere.

Chris H
+4  A: 

An array of one instance is still an array. There is simply not a special case, so you need to treat it as an array and not a single object. Non-array delete may crash.

An array of objects may be preceded by a number signifying the size of the array. If that's the case, delete[], not delete, is smart enough to pass the correct pointer to free.

Potatoswatter
+2  A: 

They are not the same. Even though delete p would compile but could potentially cause problems at runtime.

delete p will invoke operator delete(void*) where as delete [] will call operator delete[](void*). The default behavior is for delete[] to call delete but if a custom operator for delete [] has been implemented, it won't be called if you just call delete and you'll have a problem (probably a silent one).

Good rule of thumb is if you used [] in the new, use it in the delete.

Travis
Not a rule of thumb, a requirement.
GMan
A: 

with one int allocation , I checked with MVS 2005 with the below lines of code

int *p = new int[1]; delete [] p; int *c = new int[1]; delete p; int *l =new int; delete [] l;

and the program is working fine. the memory allocated is for 1 int and with delete frees for 1 int. is there any chance of memory curruption? with delete[] it calls invoked extra function "RTCCALLBACK(_RTC_Free_hook, (p, 0))" as compared to delete. what is use of RTCCALLBACK ?

Search Google for RTCCALLBACK. It's part of your debugging runtime library. As for the rest, you just repeated your question, this time with different code. Now you're using `delete[]` correctly but you've `delete` d `p` twice, which may cause a crash (even if it doesn't "on the first try").
Potatoswatter
Please click the checkmark next to your favorite answer to accept it as correct.
Potatoswatter