Do I need to call delete [] vs delete for char arrays?

I am using a library written by a colleague and found that valgrind throwing delete errors.

The problem was that char arrays of type

 char* s = new char[n]; 

followed by delete s

instead of delete[] s

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

Thus, deleting s is not really a bug per se, and valgrind just very thorough.

Will it definitely free up all memory associated with s ?

+6
c ++
source share
3 answers

If you select an array with new[] , you need to destroy it with delete[] . In general, the functions operator delete(void*) and operator delete[](void*) not guaranteed to be the same.

Contact here

+22
source share

The standard does not say anything about how the memory will be deleted - it simply says that it does not correspond to the correct new with the correct deletion - this is undefined behavior.

In fact, new[] , followed by delete , usually frees up all the memory that was allocated with new[] , but destructors for elements in this array are not called correctly. (Most of the time is not what the standard requires)

Instead of dynamically allocated arrays, you should consider using vector .

+8
source share

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

+8
source share

All Articles