在写合并数组的代码时忘了语法规范,将释放堆内存的代码写成了“delete temp[]”,在改正后发现,直接使用“delete temp”也能将堆内存完全释放,如下图所示。
使用delete temp;的效果
使用delete[] temp;的效果
可见在本例中delete和delete[]的效果相同。
原因
参考:
https://stackoverflow.com/questions/47111302/deleting-array-from-heap
对于
int* temp = new int[high - low + 1];
delete temp;
是一个未定义行为(undefined behaviour)。
未定义行为:在所使用的代码中未作规定的行为,编译器不会报错,但不同的编译器会有不同的处理方法。
在本例中只是幸运的没有发生错误,new/delete和new[]/delete[]应该成对使用。
补充
Visual Studio C++中内存分配的各个填充字符(如“cc”、“dd”……)的意义:https://stackoverflow.com/questions/127386/in-visual-studio-c-what-are-the-memory-allocation-representations
- 0xABABABAB : Used by Microsoft’s HeapAlloc() to mark “no man’s land” guard bytes after allocated heap memory
- 0xABADCAFE : A startup to this value to initialize all free memory to catch errant pointers
- 0xBAADF00D : Used by Microsoft’s LocalAlloc(LMEM_FIXED) to mark uninitialised allocated heap memory
- 0xBADCAB1E : Error Code returned to the Microsoft eVC debugger when connection is severed to the debugger
- 0xBEEFCACE : Used by Microsoft .NET as a magic number in resource files
- 0xCCCCCCCC : Used by Microsoft’s C++ debugging runtime library to mark uninitialised stack memory
- 0xCDCDCDCD : Used by Microsoft’s C++ debugging runtime library to mark uninitialised heap memory
- 0xDDDDDDDD : Used by Microsoft’s C++ debugging heap to mark freed heap memory
- 0xDEADDEAD : A Microsoft Windows STOP Error code used when the user manually initiates the crash.
- 0xFDFDFDFD : Used by Microsoft’s C++ debugging heap to mark “no man’s land” guard bytes before and after allocated heap memory
- 0xFEEEFEEE : Used by Microsoft’s HeapFree() to mark freed heap memory
粗略翻译几个认识的:
- 0xCCCCCCCC : 微软C++debug模式下标记 未初始化的栈内存
- 0xCDCDCDCD : 微软C++debug模式下标记 未初始化的堆内存
- 0xDDDDDDDD : 微软C++debug模式下标记 被释放的堆内存
- 0xFDFDFDFD : 微软C++debug模式下标记 在分配堆内存前后标记 “no man’s land”
未解决
在查看内存其他地方时,发现delete[]对内存的改动的不仅仅是int *temp = new int[10];申请的10个int空间和记录长度的4个byte。