是否有必要为char数组调用delete [] vs delete? [英] Is it necessary to call delete[] vs delete for char arrays?

查看:227
本文介绍了是否有必要为char数组调用delete [] vs delete?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用由同事写的库,并发现 valgrind 已经抛出与 delete



问题是,有像

这样的字符数组的分配

  char * s = new char [n]; 

后续使用 delete s p>

而不是 delete [] s



区别是 delete [] s 会为 s 中的每个位置的对象调用析构函数它有一个),在这种情况下,它不是因为它是一个原始类型。我相信这是真的。



所以删除s不是一个真正的错误, valgrind 只是非常彻底。



它仍然会释放所有与 s 有关的内存?

new [] 分配一个数组,你必须使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆