new 和 malloc() 的区别


在这篇文章中,我们将了解“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;
   /* Initial memory allocation */
   str = (char *) malloc(5);
   strcpy(str, "amit");
   printf("String = %s, Address = %u
", str, str); }

更新于: 2021年3月24日

881 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.