c new delete

xiliang_pan 2008-05-29 11:16:57
new 分配的 delete 不掉?
...全文
110 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
dahua010 2008-05-29
  • 打赏
  • 举报
回复
这个具体也不好解释.只能说下个人理解.

指针本身也不会知道自己的空间大小,分配的空间应该有一个标志,而越界赋值则破坏了那个标志,从而会导致释放出错.

以上是个人理解,如果不对,还请高人来解答
xiliang_pan 2008-05-29
  • 打赏
  • 举报
回复
对cert分配的空间不足时,fread对其越界赋值后delete只是释放为cert分配的空间,为什么会试图
释放掉其他空间?
Zhentiwei 2008-05-29
  • 打赏
  • 举报
回复
//FILE *fp = NULL;
//fp = fopen("C:\\1.txt","rb");
char *cert = NULL;
int len = -1,num = -1;
//len = fseek(fp,0,SEEK_END);
//num = ftell(fp);
cert = new char[len+1];
/*memset(cert,0,len+1);
len = fseek(fp,0,SEEK_SET);
//rewind(fp);
fread((void*)cert,sizeof(char),num,fp);
cert[num] = '\0';
OutputDebugString((char*)cert);
fclose(fp);
printf("%s\n",(char*)cert);
*/
delete []cert; //报错 ?

调试看看
Zhentiwei 2008-05-29
  • 打赏
  • 举报
回复
include <stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
int main()
{
char *cert = NULL;
int len = 9;
cert = new char[len+1];
cert[0] = 'a';
cert[10] = 'a';
cout<<cert<<endl;
delete []cert;
cout<<cert<<endl;
return 0;
}

我这样也没有问题啊
na_he 2008-05-29
  • 打赏
  • 举报
回复
delete t删除单个对象,
delete []t删除一组对象,如果定义了一组对象且不是内建类型,delete t只能删除一个对象,会造成内存泄漏
sukyin 2008-05-29
  • 打赏
  • 举报
回复
你那个1.txt里面有东西没有?
dahua010 2008-05-29
  • 打赏
  • 举报
回复
len = fseek(fp,0,SEEK_END);
num = ftell(fp);
cert = new char[len+1];
memset(cert,0,len+1);
len = fseek(fp,0,SEEK_SET);
fread((void*)cert,sizeof(char),num,fp);

在上面这段代码中, LZ的cert 开辟的空间过小,所以fread((void*)cert,sizeof(char),num,fp)
对cert进行了越界的赋值操作.所以导致delete的时候崩溃
sukyin 2008-05-29
  • 打赏
  • 举报
回复
怎么可能。
Zhentiwei 2008-05-29
  • 打赏
  • 举报
回复
贴出你代码看看啊
xiliang_pan 2008-05-29
  • 打赏
  • 举报
回复
FILE *fp = NULL;
fp = fopen("C:\\1.txt","rb");
char *cert = NULL;
int len = -1,num = -1;
len = fseek(fp,0,SEEK_END);
num = ftell(fp);
cert = new char[len+1];
memset(cert,0,len+1);
len = fseek(fp,0,SEEK_SET);
//rewind(fp);
fread((void*)cert,sizeof(char),num,fp);
cert[num] = '\0';
OutputDebugString((char*)cert);
fclose(fp);
printf("%s\n",(char*)cert);
delete []cert; //报错 ???

64,691

社区成员

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

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