方法1:
#include<iostream>
using namespace std;
int main(){
int *p;
p = new int;
if (!p){
cout << "allocation failure" << endl;
return 1;
}
*p = 20;
cout << *p << endl;
delete p;
return 0;
}
方法2:使用assert
#include<iostream>
#include<cassert>
using namespace std;
int main(){
int *p;
p = new int;
assert(p != 0);
*p = 20;
cout << *p << endl;
delete p;
return 0;
}
本文介绍了两种在C++中进行动态内存分配的方法,并强调了使用`new`操作符时错误处理的重要性。方法1展示了基本的内存分配和释放过程,而方法2引入了`assert`来检查指针是否为空,确保了程序在内存不足时能以适当的方式终止。通过这两个例子,读者可以更好地理解如何在实践中防止内存泄漏和处理分配失败的情况。

被折叠的 条评论
为什么被折叠?



