new 和 malloc() 之间的区别
computer programmingprogrammingmiscellaneous
在这篇文章中,我们将了解 ‘new’ 和 ‘malloc’ 之间的区别。
new
它存在于 C++、Java 和 C# 中。
它是一个可用于调用对象构造函数的运算符。
它可以被重载。
如果失败,则会引发异常。
它不需要 ‘sizeof’运算符。
它不会重新分配内存。
它可以在为对象分配内存时初始化对象。
由‘new’运算符分配的内存可以使用‘delete’运算符取消分配。
它减少了应用程序的执行时间。
示例
#include<iostream> using namespace std; int main(){ int *val = new int(10); cout << *val; getchar(); return 0; }
malloc
这是 C 语言中存在的。
它是一个不能重载的函数。
当‘malloc’失败时,它返回 NULL。
它需要‘sizeof’操作符来了解需要分配多少内存。
无法调用构造函数。
无法使用此函数初始化内存。
使用 malloc 分配的内存可以使用 free 函数释放。
使用 malloc 方法分配的内存可以使用 realloc 方法重新分配。
执行应用程序需要更多时间。
以下是 C 语言中 malloc 的示例 −
示例
#include <stdio.h> #include <stdlib.h> #include <string.h> int main () { char *str; /* 初始内存分配 */ str = (char *) malloc(5); strcpy(str, "amit"); printf("String = %s, Address = %u
", str, str); }