malloc() vs new &&& delete and free() in C++
malloc() vs new
Following are the differences between malloc() and operator new.
1) new calls constructors, while malloc() does not. In fact primitive data types (char, int, float.. etc) can also be initialized with new. For example, below program prints 10.
3) new returns exact data type, while malloc() returns void *.
1) new calls constructors, while malloc() does not. In fact primitive data types (char, int, float.. etc) can also be initialized with new. For example, below program prints 10.
#include<iostream> using namespace std; int main() { int *n = new int(10); // initialization with new() cout<<*n; getchar(); return 0; }2) new is an operator, while malloc() is a fucntion.
3) new returns exact data type, while malloc() returns void *.
delete and free() in C++
In C++, delete operator should only be used either for the pointers pointing to the memory allocated using new operator or for a NULL pointer, and free() should only be used either for the pointers pointing to the memory allocated using malloc() or for a NULL pointer.
#include<stdio.h> #include<stdlib.h> int main() { int x; int *ptr1 = &x; int *ptr2 = (int *)malloc(sizeof(int)); int *ptr3 = new int; int *ptr4 = NULL; /* delete Should NOT be used like below because x is allocated on stack frame */ delete ptr1; /* delete Should NOT be used like below because x is allocated using malloc() */ delete ptr2; /* Correct uses of delete */ delete ptr3; delete ptr4; getchar(); return 0; }
Comments
Post a Comment