New vs Malloc()

  1. Calling Constructors: new calls constructors, while malloc() does not. In fact, primitive data types (char, int, float.. etc) can also be initialized with new. Ex: int *n = new int(10); 
  2. operator vs function: new is an operator, while malloc() is a function.
  3. return type: new returns exact data type, while malloc() returns void *.
  4. Failure Condition: On failure, malloc() returns NULL were as new throws bad_alloc exception.
  5. Memory: In the case of new, memory is allocated from free store whereas in malloc() memory allocation is done from the heap.
  6. Overriding: We are allowed to override the new operator whereas we can not override the malloc() function legally.
  7. Size: Required size of memory is calculated by the compiler for new, whereas we have to manually calculate the size for malloc().
  8. Buffer Size: malloc() allows to change the size of the buffer using realloc() while new doesn’t

Comments