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 delete
s?
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 delete
s?
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.
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
.
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
.
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 ?