请教 :一个异常问题中出现的debug assertion failed错误的问题 ??

haifengwhb 2008-03-19 08:34:00
#include<iostream.h>
#include<string.h>
class MyException
{
public:
char *cause;
MyException(char *in)
{
cause=new char[21];
strcpy(cause,in);
}
void printmessage()
{
cout<<"Error!"<<cause<<endl;
delete[] cause;
}
~MyException()
{
delete[] cause;
}
};
class person
{ int age;
public:
void get()
{
cout<<"Enter age:"<<endl;
cin>>age;
MyException e("Problem with age!");
if(age>100||age<0)
throw e;
else
cout<<"Correct age. : )";
}
};
void main()
{
person pe;
try
{
pe.get();
}
catch(MyException &x)
{
x.printmessage();
}
}



vc6.0编译通过,运行:当输入0-100之间的数时运行正常,当输入〉100的数时程序报错:

debug assertion failed!

program:c:\documents and settings\administor\debug\excep_test.exe

file:dbgdel.cpp

line:47

expression: _BLOCK_TYPE_IS_VAILD(pHead->nBlockUse)

不知为何出现这个错误???应该是cause指针的问题,

有几个问题请您解答:
1. MyException e 的生命周期是否为if{}块??
2.为什么把char *cause;替换成char cause[21];数组后就不会出现上述问题?
3.catch处理器能否接受一个传引用x??
感谢回答!

...全文
113 6 打赏 收藏 举报
写回复
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
haifengwhb 2008-03-21
  • 打赏
  • 举报
回复
哦,我明白了,谢谢回答!!!!!!!!!!!!!!
ttkk_2007 2008-03-19
  • 打赏
  • 举报
回复

1. MyException e 的生命周期是否为if{}块??
2.为什么把char *cause;替换成char cause[21];数组后就不会出现上述问题?
3.catch处理器能否接受一个传引用x??
////////////////////////////////////
1.e的生命期在try块内,抛出异常的时候会将对象拷贝给一个临时对象
2.你程序问题之一就是没有拷贝构造函数,因此调用了浅拷贝,使e得cause和临时对象的cause指向同一块内存,释放的时候就出问题了
你不new的话,就没这个问题,各自占各自的内存
3.能
jieao111 2008-03-19
  • 打赏
  • 举报
回复
3。可以的把
jieao111 2008-03-19
  • 打赏
  • 举报
回复
1。是的,,抛出的是一个拷贝
ttkk_2007 2008-03-19
  • 打赏
  • 举报
回复

class MyException
{
public:
char *cause;
MyException(char *in)
{
cause=new char[21];
strcpy(cause,in);
}
MyException(MyException &me){ //要定义一个拷贝构造函数
cause = new char[strlen(me.cause) + 1];
strcpy(cause, me.cause);
}
void printmessage()
{
cout <<"Error!" <<cause <<endl;
//delete[] cause; //去掉
}
~MyException()
{
delete[] cause;
}
};
class person
{ int age;
public:
void get()
{
cout <<"Enter age:" <<endl;
cin>> age;
MyException e("Problem with age!");
if(age> 100 ||age <0)
throw e;
else
cout <<"Correct age. : )";
}
};
void main()
{
person pe;
try
{
pe.get();
}
catch(MyException &x)
{
x.printmessage();
}
}
jieao111 2008-03-19
  • 打赏
  • 举报
回复
#include <iostream.h> 
#include <string.h>
class MyException
{
public:
char *cause;
MyException(char *in)
{
cause=new char[21];
strcpy(cause,in);
}
void printmessage()
{
cout < <"Error!" < <cause < <endl;
delete[] cause;
}
~MyException()
{
delete[] cause;
}
};
class person
{ int age;
public:
void get()
{
cout < <"Enter age:" < <endl;
cin> > age;
MyException e("Problem with age!");
if(age> 100 ¦ ¦age <0)
throw e;
else
cout < <"Correct age. : )";
}
};
void main()
{
person pe;
try
{
pe.get();
}
catch(MyException &x)
{
x.printmessage();
}
}

发帖
C++ 语言

6.3w+

社区成员

C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
帖子事件
创建了帖子
2008-03-19 08:34
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下