1.
C语言中,使用malloc/calloc分配空间后,检查分配是否成功的方法是:判断返回值是否为NULL。例如:
int *a = malloc(SIZE); if (a == NULL) return -1;
2.
标准C++中new失败默认抛出std::bad_alloc异常,故检查返回值的方法无效,正确的方法是:用try,catch捕获异常。例如:
try{ int *a = new int[SIZE]; } catch (std::bad_alloc &e){ std::cout << e.what() << std::endl; return -1; }
3.
标准C++提供了一个方法可抑制new抛出异常,从而通过返回值是否为NULL来处理。
抑制new操作异常抛出,主要是为了兼容早期的C++,故不推荐。
int *a = new (std::nothrow)int[SIZE]; if (a == NULL) return -1;
参考自:http://hi.baidu.com/bellgrade/item/179ff5374b74eef6e7bb7aa6