C / C ++中的new / delete和malloc / free有什么区别?
新增/删除
新运算符请求在堆中分配内存。如果有足够的内存可用,则将内存初始化为指针变量并返回其地址。
delete运算符用于取消分配内存。用户具有通过此delete运算符取消分配创建的指针变量的特权。
这是C++语言中的new/delete运算符的示例,
示例
#include <iostream>
using namespace std;
int main () {
int *ptr1 = NULL;
ptr1 = new int;
float *ptr2 = new float(299.121);
int *ptr3 = new int[28];
*ptr1 = 28;
cout << "Value of pointer variable 1 : " << *ptr1 << endl;
cout << "Value of pointer variable 2 : " << *ptr2 << endl;
if (!ptr3)
cout << "Allocation of memory failed\n";
else {
for (int i = 10; i < 15; i++)
ptr3[i] = i+1;
cout << "Value of store in block of memory: ";
for (int i = 10; i < 15; i++)
cout << ptr3[i] << " ";
}
delete ptr1;
delete ptr2;
delete[] ptr3;
return 0;
}输出结果
这是输出
Value of pointer variable 1 : 28 Value of pointer variable 2 : 299.121 Value of store in block of memory: 11 12 13 14 15
malloc/免费
该函数malloc()用于分配请求的字节大小,并返回指向已分配内存的第一个字节的指针。如果失败,则返回空指针。
该函数free()用于通过释放分配的内存malloc()。它不会更改指针的值,这意味着它仍指向相同的内存位置。
这是C语言中的malloc/free的示例,
示例
#include <stdio.h>
#include <stdlib.h>
int main() {
int n = 4, i, *p, s = 0;
p = (int*) malloc(n * sizeof(int));
if(p == NULL) {
printf("\nError! memory not allocated.");
exit(0);
}
printf("\nEnter elements of array : ");
for(i = 0; i < n; ++i) {
scanf("%d", p + i);
s += *(p + i);
}
printf("\nSum : %d", s);
free(p);
return 0;
}输出结果
这是输出-
Enter elements of array : 32 23 21 8 Sum : 84