new与delete必须成对使用

来源:互联网 发布:网上网络兼职是真的吗 编辑:程序博客网 时间:2024/06/05 03:07

char  *buff = new char[reslen]; char *utfbuff =new char[reslen];  ....  ....  delete  buff;  delete  utfbuff;  


代码如上:


后果:
这段代码运行没有引发运行时错误,但是本身是存在隐患的,如果后续对*(buff+1)进行了误使用,使用了本应该释放了的内存空间。




bug分析:


对于基本类型如char int 等,delete 还是delete[]是一样的,都能够释放掉内存。
但是对于自定义的类,比如String *str =new string[10],用delete str和delete []str的区别是delete   str只对str[0]调用了析构函数,而delete   [] str则对str数组里的每
个元素都调用了析构函数,这样如果后续对*(str+1)进行了使用,就会使用到你本来打算已经释放掉的内存空间了。
也就是说,当仅仅是delete str的时候,str+1,str+2,.....等就成为了本应“在野”的“执政”指针。


正确情况如下:

 


char  *buff = new char[reslen];char *utfbuff =new char[reslen];........delete [] buff;delete [] utfbuff;




原创粉丝点击