Asked  7 Months ago    Answers:  5   Viewed   46 times

What is the difference between delete and delete[] operators in C++?

 Answers

60

The delete operator deallocates memory and calls the destructor for a single object created with new.

The delete [] operator deallocates memory and calls destructors for an array of objects created with new [].

Using delete on a pointer returned by new [] or delete [] on a pointer returned by new results in undefined behavior.

Tuesday, June 1, 2021
 
dmp
answered 7 Months ago
dmp
37

Whether this leads to a memory leak, wipes your hard disk, gets you pregnant, makes nasty Nasal Demons chasing you around your apartment, or lets everything work fine with no apparent problems, is undefined. It might be this way with one compiler, and change with another, change with a new compiler version, with each new compilation, with the moon phases, your mood, or depending on the number of neutrinos that passed through the processor on the last sunny afternoon. Or it might not.

All that, and an infinite number of other possibilities are put into one term: Undefined behavior:

Just stay away from it.

Tuesday, June 1, 2021
 
IvanH
answered 7 Months ago
25

From the standard (5.3.5/2) :

In the first alternative (delete object), the value of the operand of delete shall be a pointer to a non-array object or a pointer to a sub-object (1.8) representing a base class of such an object (clause 10). If not, the behavior is undefined.

In the second alternative (delete array), the value of the operand of delete shall be the pointer value which resulted from a previous array new-expression. If not, the behavior is undefined.

So no : they are in no way equivalent !

Friday, June 4, 2021
 
lewiguez
answered 7 Months ago
96

Do it allocate exact 10 bytes

That's implementation dependant. The guarantee is "at least 10 chars".

Where information about size is stored?

That's implementation dependant.

Is there any header for each new which contain information about number of byte allocated by new?

That's implementation dependant.

By "that's implementation dependant" I mean it's not defined in the standard.

Tuesday, August 17, 2021
 
PedroKTFC
answered 4 Months ago
55

From the C++ Standard, section 5.3.5/2:

the value of the operand of delete shall be the pointer value which resulted from a previous array new-expression. If not, the behaviour is undefined

Monday, August 23, 2021
 
LukeP
answered 4 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share