这只是对某些操作系统和编译器中的一些“未定义”行为的说明。希望这能帮助人们调试他们的代码。
测试1
#include <iostream>
using namespace std;
int main()
{
int *p = new int[5];
cout << "pass" << endl;
delete p;
return 0;
}
测试2
#include <iostream>
using namespace std;
int main()
{
int *p = new int;
cout << "pass" << endl;
delete[] p;
return 0;
}
测试 3
#include <iostream>
using namespace std;
struct C {
C() { cout << "construct" << endl; }
~C() { cout << "destroy" << endl; }
};
int main()
{
C *p = new C[5];
cout << "pass" << endl;
delete p;
return 0;
}
测试4
#include <iostream>
using namespace std;
struct C {
C() { cout << "construct" << endl; }
~C() { cout << "destroy" << endl; }
};
int main()
{
C *p = new C;
cout << "pass" << endl;
delete[] p;
return 0;
}
- Windows 7 x86,使用msvc 2010编译。默认选项编译,即启用异常处理程序。
测试1
pass
测试 2
pass
测试 3
construct
construct
construct
construct
construct
pass
destroy
测试 4
construct
pass
destroy
destroy
destroy
destroy
destroy
destroy
destroy
...
- Mac OS X 10.8.5,llvm-gcc 4.2或gcc-4.8会生成相同的输出结果。
测试1
pass
测试2
pass
测试3
construct
construct
construct
construct
construct
pass
destroy
a.out(71111) malloc: *** error for object 0x7f99c94000e8: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
zsh: abort ./a.out
测试4
construct
pass
a.out(71035) malloc: *** error for object 0x7f83c14000d8: pointer being freed was not allocated
*** set a breakpoint in malloc_error_break to debug
zsh: abort ./a.out
- Ubuntu 12.04,AMD64,gcc 4.7
测试1
pass
测试 2
pass
测试3
construct
construct
construct
construct
construct
*** glibc detected *** ./a.out: munmap_chunk(): invalid pointer: 0x0000000001f10018 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x7eb96)[0x7fe81d878b96]
./a.out[0x400a5b]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xed)[0x7fe81d81b76d]
./a.out[0x4008d9]
======= Memory map: ========
....
zsh: abort (core dumped) ./a.out
测试4
construct
destroy
destroy
destroy
destroy
destroy
destroy
destroy
destroy
...
destroy
destroy
*** glibc detected *** ./a.out: free(): invalid pointer: 0x00000000016f6008 ***
======= Backtrace: =========
/lib/x86_64-linux-gnu/libc.so.6(+0x7eb96)[0x7fa9001fab96]
./a.out[0x400a18]
/lib/x86_64-linux-gnu/libc.so.6(__libc_start_main+0xed)[0x7fa90019d76d]
./a.out[0x4008d9]
======= Memory map: ========
...
zsh: abort (core dumped) ./a.out
IP_ADAPTER_INFO
不再是POD类型时会发生什么?您是否打算编辑所有的代码?由于您已经使用了C++标签,因此应该考虑使用std::vector
。(如果需要更详细的上下文信息,请提供更多的背景信息) - Kirill V. Lyadvinsky