内存释放

sjbird331 2009-07-31 05:05:50
在VC下写了一个小程序,如下:
char *strCB = NULL;
strCB = new char[100];
memcpy(strCB, strCombox, 100);
strCB[100] = '\0';
int Level = DefineLevel(strCB);
char *strLevel = new char[1];
sprintf(strLevel, "%d", Level);

delete [] strCB;
strCB = NULL;
delete strLevel;
strLevel = NULL;
其中,strCombox为字符串,DefineLevel(char *str)为一函数,我在最后进行内存释放时用了后面四句,可是编译通过,一运行就提示错误,“DAMAGE: after Normal block(#137) at 0x00422830”,请问这是怎么回事?谢谢
...全文
85 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
sjbird331 2009-07-31
  • 打赏
  • 举报
回复
谢谢
hailang_Boy 2009-07-31
  • 打赏
  • 举报
回复
strCB[100] = '\0'; 很危险,为了保险期间最好这样写

char *strCB = NULL;
strCB = new char[strLen(strCombox)+1];
memcpy(strCB, strCombox, strLen(strCombox));
strCB[strLen(Combox)] = '\0';
.....
delete []strCB; //谨记
Treazy 2009-07-31
  • 打赏
  • 举报
回复
1 strCB的有效空间为100个字节,strCB[100] = '\0'很危险
2 char *strLevel = new char[1]; ... delete strLevel;
new[] 最好与 delete[]配对使用
pengzhixi 2009-07-31
  • 打赏
  • 举报
回复
memcpy(strCB, strCombox, 100);//这里是否应该是99
strCB[100] = '\0'; //这里是否应该是strCB[99]='\0';
delete strLevel; //这里是否应该是delete []strLevel;
mstlq 2009-07-31
  • 打赏
  • 举报
回复
既然是char *strLevel = new char[1];
那么还是请老实一点使用delete []strLevel吧^_^

64,641

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧