C/C++ 中 new/delete 和 malloc/ free 的区别是什么?
new/ delete
new 运算符要求在堆中分配内存。如果内存充足,它会将内存初始化为指针变量并返回其地址。
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/ free
函数 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;
}输出
以下是 output −
Enter elements of array : 32 23 21 8 Sum : 84
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP