65,210
社区成员
发帖
与我相关
我的任务
分享#include <iostream>
#include <new>
#include <cstdlib>
using namespace std;
struct Big
{
double stuff[20000];
};
int main()
{
Big* pb;
try
{
cout<<"Trying to get a big block of memory:\n";
pb=new Big[10000];
cout<<"Get past the new requeset:\n";
}
catch(bad_alloc &ba)
{
cout<<"Caught the exception!\n";
cout<<ba.what()<<endl;
exit(EXIT_FAILURE);
}
if(pb!=0)
{
pb[0].stuff[0]=4;
cout<<pb[0].stuff[0]<<endl;
}
else
{
cout<<"Pb is null pointer\n";
}
delete []pb;
return 0;
}
[code=C/C++]
//我的理解是 4*10000 * 20000是没抛出异常,但是VC不同于DEV-c出现,没有结果输出,
//很奇怪,你把程序改成下面VC也可以正常输出了。
#include <iostream>
#include <new>
#include <cstdlib>
using namespace std;
struct Big
{
char stuff[0x7fffffff];
};
int main()
{
Big* pb;
try
{
cout<<"Trying to get a big block of memory:\n";
pb = new Big;
cout<<"Get past the new requeset:\n";
}
catch(bad_alloc &ba)
{
cout<<"Caught the exception!\n";
cout<<ba.what()<<endl;
exit(EXIT_FAILURE);
}
/* if(pb!=0)
{
pb[0].stuff[0]=4;
cout<<pb[0].stuff[0]<<endl;
}
else
{
cout<<"Pb is null pointer\n";
}
delete pb;
*/
return 0;
}
struct Big
{
double stuff[20000];
}; pb=new Big[10000];
//20000时的结果:
Trying to get a big block of memory:
Get past the new requeset:
4
请按任意键继续. . .
//200000时的结果:
Trying to get a big block of memory:
Caught the exception!
St9bad_alloc
请按任意键继续. . .
我的是1GB physical memory