Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it necessary to call delete[] vs delete for char arrays?

Tags:

c++

I'm utilizing a library written by a collegue and discovered that valgrind was spewing out errors related to the delete.

The problem was that there were allocations of char arrays like

char* s = new char[n];

followed up later with delete s

instead of delete[] s

He tells me that the difference is really that delete[] s will call a destructor for the object at each position in s (if it has one), in this case it doesn't because it's a primitive type. I believe that is true.

So delete s is not really a bug as such and valgrind is just being very thorough.

Will it still definitely free all the memory associated with s?

like image 774
hookenz Avatar asked Sep 09 '10 22:09

hookenz


3 Answers

If you allocate an array using new[], you have to destroy it using delete[]. In general, the functions operator delete(void*) and operator delete[](void*) aren't guaranteed to be the same.

Refer here

like image 103
Michael Williamson Avatar answered Oct 21 '22 05:10

Michael Williamson


Forget about destructors. The difference between new/delete and new[]/delete[] is that these are two completely unrelated, independent memory allocation mechanisms. They cannot be mixed. Using delete to deallocate memory allocated with new[] is no different than using free for the same purpose.

like image 30
AnT Avatar answered Oct 21 '22 05:10

AnT


The standard says nothing about how the memory will get deleted -- it merely says that to not match the correct new with the correct delete is undefined behavior.

Actually, new[] followed by delete usually frees all the memory that was allocated with new[], but destructors for the items in that array are not called correctly. (Most of the time -- not that the standard mandates that)

Rather than dynamically allocated arrays, you should consider use of vector.

like image 36
Billy ONeal Avatar answered Oct 21 '22 05:10

Billy ONeal