Malloc Vs New

You might also like

Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 1

malloc vs new keyword

===========================
Both malloc() and new, are used to allocate memory dynamically in the heap. the
functionality of these are seems to be the same but they differ in the following
ways.
1) malloc() is a C library function that can be used in c++ while "new" is a
operator or keyword which is available in C++ only.

2) "new" calls the contructor of the class when we use to allocate memory
dynamically while malloc() does not.

3) the "new" operator returns the specific type of pointer as it is declared hence,
there is not required to type-cast to assign the pointer. while malloc() return
void pointer hence, typecasting is required to assign the pointer.

4) required space is automatically calculate by new keyword when we use this to


allocate the memory dynamically. but, in case of malloc() function , required size
of memory is passed as argument to this function.

5) If sufficient memory is not available in heap then "new" operator throws an


exception while malloc() function returns the NULL pointer.

example -
#include <iostream>
using namespace std;

class student {
public:
student() {
cout << endl << "student class constructor";
}
};

int main() {

int *a = new int(10);


cout << endl << "value of a : " << *a;

int *b = new int;


*b = 21;
cout << endl << "value of b : " << *b;
// new keyword calls the constructor of class during the allocation memeory
dynamically.
student *ptr = new student; // output => student class contructor

student *ptr1 = (student*)malloc(sizeof(student)); // here, constructor is not


called.

return EXIT_SUCCESS;
}

You might also like