问题描述
你好,
如何处理以下事项:
------>
#include< iostream>
使用命名空间std;
int main()
{
int n = 0x7FFFFFFF;
char * pp = new char(n);
if(pp!= NULL){
pp [0] = 0;
pp [n-1] = 0;
cout<< "确定]; <<结束;
}否则{
cout<< " FAILED" <<结束;
}
}
------>
编译好,但是我运行它,我得到一个分段错误。我认为测试一个NULL值足够用于测试内存分配(或者
也许这是一个错误?我使用gcc(GCC)3.3.4)
问候,
jjleto
Hello,
How do I handle the following :
------>
#include <iostream>
using namespace std;
int main()
{
int n = 0x7FFFFFFF;
char *pp = new char(n);
if ( pp != NULL ) {
pp[0] = 0;
pp[n-1] = 0;
cout << "OK" << endl;
} else {
cout << "FAILED" << endl;
}
}
------>
It compiles OK, but when I run it, I get a segmentation fault. I thought
that testing a NULL value was enough for testing memory allocation (or
perhaps it is a bug ? I use gcc (GCC) 3.3.4)
Regards,
jjleto
推荐答案
Sharad
Sharad
谢谢,分段错误实际上是因为你给的原因。
然而,我在运行这个程序时仍然有错误(放弃
但不是段错误)
怎么做我用新的测试内存分配?
Thanks, the segmentation fault was actually for the reason you gave.
Nevertheless, I still have an error when running this program ("give up"
but not a segfault)
How do I test memory allocation with new ?
异常。你需要在try-catch块中包装new(捕获
std :: bad_alloc)。
Sharad
I told you in my earlier reply too that new throws std::bad_alloc on
exception. You need to wrap the new in a try-catch block (catching
std::bad_alloc).
Sharad
这篇关于如何用新的测试内存分配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!