是否有必要为char数组调用delete [] vs delete? [英] Is it necessary to call delete[] vs delete for char arrays?
问题描述
我正在使用由同事写的库,并发现 valgrind
已经抛出与 delete
。
问题是,有像
这样的字符数组的分配 char * s = new char [n];
后续使用 delete s
p>
而不是 delete [] s
区别是 delete [] s
会为 s
中的每个位置的对象调用析构函数它有一个),在这种情况下,它不是因为它是一个原始类型。我相信这是真的。
所以删除s不是一个真正的错误, valgrind
只是非常彻底。
它仍然会释放所有与 s
有关的内存?
delete []
。通常,不保证函数 operator delete(void *)
和 operator delete [](void *)
请参阅此处
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
?
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
这篇关于是否有必要为char数组调用delete [] vs delete?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!