Possible Duplicate:
delete vs delete[] operators in C++
I've written a class that contains two pointers, one is char* color_
and one in vertexesset* vertex_
where vertexesset
is a class I created. In the destractor I've written at start
delete [] color_; delete [] vertex_;
When It came to the destructor it gave me a segmentation fault.
Then I changed the destructor to:
delete [] color_; delete vertex_;
And now it works fine. What is the difference between the two?
delete is used for one single pointer and delete[] is used for deleting an array through a pointer.
What is the difference between delete and delete[] in C++? Explanation: delete is used to delete a single object initiated using new keyword whereas delete[] is used to delete a group of objects initiated with the new operator.
Delete[] operator is used to deallocate that memory from heap. New operator stores the no of elements which it created in main block so that delete [] can deallocate that memory by using that number.
Delete is an operator that is used to destroy array and non-array(pointer) objects which are created by new expression. Delete can be used by either using Delete operator or Delete [ ] operator. New operator is used for dynamic memory allocation which puts variables on heap memory.
You delete []
when you new
ed an array type, and delete
when you didn't. Examples:
typedef int int_array[10]; int* a = new int; int* b = new int[10]; int* c = new int_array; delete a; delete[] b; delete[] c; // this is a must! even if the new-line didn't use [].
delete
and delete[]
are not the same thing! Wikipedia explains this, if briefly. In short, delete []
invokes the destructor on every element in the allocated array, while delete
assumes you have exactly one instance. You should allocate arrays with new foo[]
and delete them with delete[]
; for ordinary objects, use new
and delete
. Using delete[]
on a non-array could lead to havoc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With