delete vs delete[] [duplicate]
Asked Answered
J

4

103

Possible Duplicate:
What is the difference between delete and delete[]?

When I was taught C++, this was a long time ago. I was told to never use delete but delete[] as performing delete[] on a single object will be equivalent to delete. Knowing not to trust teachers too much I wonder, Is this true?

Is there ever a reason to call delete instead of delete[]?

I've scanned the possibly related questions in SO, but haven't found any clear answer.

Jerrybuilt answered 23/11, 2010 at 11:34 Comment(7)
/me throws up a little. Did they recommend you always call new[1] as well?Disadvantage
Don't trust them when they tell "never". All strong statements are wrong.Pahlavi
Actually there're small range of cases where you need to use delete[] in C++. It is better to use std::vector or boost::array.Pahlavi
@Kirill "All strong statements are wrong." this statement is paradoxical.Handset
If use valgrind --leak-check=full ./(binary name) you will get warning "Mismatched free() / delete / delete []". It is better to compile your program with valgrind to check for memory related queries.Medea
lol, "All strong statements are wrong", is a strong statement.Venereal
I'm pretty sure that was his joke.Sizar
O
118

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 !

Ordeal answered 23/11, 2010 at 11:38 Comment(0)
R
55

delete [] is "vector delete" and corresponds to vector new, i.e. new[].

You must use the matching pair of allocators. E.g. malloc/free, new/delete, new[]/delete[], else you get undefined behavior.

Rosenwald answered 23/11, 2010 at 11:39 Comment(2)
The word "vector" in the response should be changed to "native C-style array" ? Otherwise it is just a bit confusing perhaps.Epizootic
No, vector and scalar new/delete are well understood terms.Rosenwald
H
36

No! you call delete[] when you allocate with new[], otherwise you call delete.

What teacher told you leads to undefined behaviour and, if you are lucky, an application crash.

Huihuie answered 23/11, 2010 at 11:38 Comment(0)
S
11

delete is used to delete a single object, while delete[] is used to delete an array of objects. Check this link for more info.

Subway answered 23/11, 2010 at 11:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.