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;