Difference between new and malloc( )

Computer ProgrammingProgrammingMiscellaneous

In this post, we will understand the difference between ‘new’ and ‘malloc’.

new

  • It is present in C++, Java, and C#.

  • It is an operator that can be used to call the constructor of the object.

  • It can be overloaded.

  • If it fails, an exception is thrown.

  • It doesn’t need the ‘sizeof’ operator.

  • It doesn’t reallocate memory.

  • It can initialize an object when allocating memory for it.

  • The memory allocated by ‘new’ operator can be de-allocated using ‘delete’ operator.

  • It reduces the execution time of the application.

Example

#include<iostream>
using namespace std;
int main(){
   int *val = new int(10);
   cout << *val;
   getchar();
   return 0;
}

malloc

  • This is present in C language.

  • It is a function that can’t be overloaded.

  • When ‘malloc’ fails, it returns NULL.

  • It requires the ‘sizeof’ operator to know how much memory has to be allotted.

  • It can’t call a constructor.

  • Memory can’t be initialized using this function.

  • The memory allocated using malloc can be deallocated using free function.

  • Memory allocated by malloc method can be reallocated using realloc method.

  • It requires more time to execute applications.

Following is the example of malloc in C language −

Example

#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\n", str, str);
}
raja
Published on 24-Mar-2021 12:47:32
Advertisements