Question 11: Which of the following statements describe the result when standard new cannot allocate the requested storage in C+

A. It throws a bad_alloc exception.

B. It returns null.

C. It returns silently with no effect on the expression.

D. It throws an insufficient_memory exception.

E. It logs an error message to the mem_err.log file.

A

有问题代码

int main(int argc, char* argv[]) { char *p = NULL; p = new char[1024]; if (NULL == p) { cout << "error" << endl; return -1; } delete []p; return 0; }

 

正确代码

 

new失败会抛出异常,我们可以这样子写代码。
# include <iostream> # include <exception> using namespace std; int main() { try { int * i = new int[1000]; } catch (exception e) { cout << e.what() << endl; } return 0; }

 

或者

 

# include <iostream> using namespace std; int main() { int * i = NULL; i = new(nothrow) int[1000]; if (i == NULL) { cout << "bad allocation" << endl; return -1; } return 0; }

你可能感兴趣的:(c,exception,null,delete,include,Allocation)