C++常见错误之一   new[]与delete[]

5 11 月, 2009 by admin Leave a reply »

int *data;

data=new int[100];

delete data;

以上程序在Visual C++ 6.0中是正确的,然而在最新的ANSI/ISO C++标准中,它却是错误的。

在以往的日子里,我也一直这么写。昨日在使用CodeGuard除错,发现在delete data一行时报告资源类型不匹配。一查CodeGuard报告,提示使用new []形式创建的资源要使用delete []释放。所以正确的程序应该如下:

int *data;

data=new int[100];

delete[] data;

以上的程序在 Borland C++ Builder 6 中测试通过,CodeGuard对未修改的错误程序报告如下:

Error 00019. 0x350010 (Thread 0x04F4):
Resource type mismatch: a(n) object was expected.
delete(0x00CF5244)

Call Tree:
0x004011C0(=NDTest.exe:0x01:0001C0) D:\Program Files\Borland\CBuilder6\Projects\NDTest\MainUnit.cpp#15
0x3266FFB3(=CC3260.DLL:0x01:06EFB3)

The object array (0x00CF5244) [size: 400 bytes] was created with new[]
Call Tree:
0x004011B4(=NDTest.exe:0x01:0001B4) D:\Program Files\Borland\CBuilder6\Projects\NDTest\MainUnit.cpp#13
0x3266FFB3(=CC3260.DLL:0x01:06EFB3)

——————————————
Functions called:
delete (25 times)
realloc (1 times)
memcpy (1 times)
delete[] (2 times)
free (15 times)
new[] (15 times)
new (29 times)
calloc (5 times)
malloc (9 times)
Resource types used:
object array (15 allocs, 14 max)
object (29 allocs, 17 max)
memory block (15 allocs, 10 max)
Modules used:
00400000 05/13/2003 10:56:46 D:\Program
Files\Borland\CBuilder6\Projects\NDTest\NDTest.exe
0CD00000 01/30/2002 17:38:38 D:\PROGRA~1\Borland\CBUILD~1\Bin\CG32.DLL
32600000 01/30/2003 06:04:00 D:\PROGRA~1\Borland\CBUILD~1\Bin\CC3260.DLL
65D20000 07/22/2002 12:05:04 C:\WINNT\System32\USP10.dll
6C330000 07/22/2002 12:05:04 C:\WINNT\System32\LPK.DLL
75E00000 07/22/2002 12:05:04 C:\WINNT\System32\IMM32.DLL
77D90000 11/11/2002 15:33:44 C:\WINNT\system32\ADVAPI32.DLL
77DF0000 11/04/2002 10:58:50 C:\WINNT\system32\USER32.DLL
77E60000 11/04/2002 10:58:54 C:\WINNT\system32\KERNEL32.DLL
77F40000 07/23/2002 16:34:08 C:\WINNT\system32\GDI32.dll
77F80000 04/04/2003 15:47:22 C:\WINNT\system32\ntdll.dll
786F0000 11/20/2002 16:53:24 C:\WINNT\system32\RPCRT4.dll
==========================================

Advertisement

发表回复

You must be logged in to post a comment.
鄂ICP备09027626号