Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The difference between delete and delete[] in C++ [duplicate]

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?

like image 813
SIMEL Avatar asked Jan 12 '11 15:01

SIMEL


People also ask

What is the difference between delete [] and delete?

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 ++? Mcq?

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.

How does delete [] know how many elements to delete?

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.

What does delete [] mean in C++?

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.


2 Answers

You delete [] when you newed 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 []. 
like image 183
etarion Avatar answered Oct 05 '22 01:10

etarion


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.

like image 42
EmeryBerger Avatar answered Oct 05 '22 00:10

EmeryBerger