C/C++中的动态内存分配是指由程序员手动进行内存分配。动态分配的内存在堆上分配,非静态和局部变量在栈上分配内存(有关详细信息,请参阅内存布局 C 程序)。
什么是应用程序?
它与分配给普通变量的内存有何不同?
对于“int a”、“char str[10]”等普通变量,内存会自动分配和释放。对于像“int *p = new int[10]”这样的动态分配内存,程序员有责任在不再需要时释放内存。如果程序员不释放内存,则会导致内存泄漏(直到程序终止时才会释放内存)。
在 C++ 中如何分配/释放内存?
C 使用malloc() 和 calloc()函数在运行时动态分配内存,并使用 free() 函数释放动态分配的内存。C++ 支持这些函数并且还有两个操作符new和delete以更好和更简单的方式执行分配和释放内存的任务。
这篇文章是关于 new 和 delete 操作符的。
new operator
new 运算符表示对 Free Store 的内存分配请求。如果有足够的内存可用,new 运算符会初始化内存并将新分配和初始化的内存的地址返回给指针变量。
pointer-variable = new data-type;
// Pointer initialized with NULL
// Then request memory for the variable
int *p = NULL;
p = new int;
OR
// Combine declaration of pointer
// and their assignment
int *p = new int;
pointer-variable = new data-type(value);
Example:
int *p = new int(25);
float *q = new float(75.25);
// Custom data type
struct cust
{
int p;
cust(int q) : p(q) {}
};
cust* var1 = new cust; // Works fine, doesn't require constructor
OR
cust* var1 = new cust(); // Works fine, doesn't require constructor
cust* var = new cust(25) // Notice error if you comment this
指针变量=新数据类型[大小];
示例:
int *p = new int[10]
普通数组声明与使用 new
声明普通数组和使用 new 分配一块内存是有区别的。最重要的区别是,普通数组由编译器释放(如果数组是本地的,则在函数返回或完成时释放)。但是,动态分配的数组始终保留在那里,直到它们被程序员释放或程序终止。
如果在运行时没有足够的内存可用怎么办?
如果堆中没有足够的内存来分配,新请求通过抛出 std::bad_alloc 类型的异常来指示失败,除非“nothrow”与 new 运算符一起使用,在这种情况下它返回一个 NULL 指针(滚动到本节中的“新运算符的异常处理”部分文章)。因此,在使用 it 程序之前检查 new 生成的指针变量可能是个好主意。
int *p = new(nothrow) int;
if (!p)
{
cout << "内存分配失败\n";
}
删除运算符
由于释放动态分配的内存是程序员的责任,因此 C++ 语言为程序员提供了删除运算符。
句法:
// 释放指针变量指向的内存
delete pointer-variable;
这里,指针变量是指向由new创建的数据对象的指针。
例子:
删除 p;
删除q;
要释放指针变量指向的动态分配的数组,请使用以下形式的delete:
// 释放内存块
// 指针变量指向
delete[] pointer-variable;
示例:
// 它将释放整个数组
// p 所指向的。
删除[] p;
// C++ program to illustrate dynamic allocation
// and deallocation of memory using new and delete
#include
using namespace std;
int main ()
{
// Pointer initialization to null
int* p = NULL;
// Request memory for the variable
// using new operator
p = new(nothrow) int;
if (!p)
cout << "allocation of memory failed\n";
else
{
// Store value at allocated address
*p = 29;
cout << "Value of p: " << *p << endl;
}
// Request block of memory
// using new operator
float *r = new float(75.25);
cout << "Value of r: " << *r << endl;
// Request block of memory of size n
int n = 5;
int *q = new(nothrow) int[n];
if (!q)
cout << "allocation of memory failed\n";
else
{
for (int i = 0; i < n; i++)
q[i] = i+1;
cout << "Value store in block of memory: ";
for (int i = 0; i < n; i++)
cout << q[i] << " ";
}
// freed the allocated memory
delete p;
delete r;
// freed the block of allocated memory
delete[] q;
return 0;
}
输出:
p 的值:29
r 的值:75.25
存储在内存块中的值:1 2 3 4 5