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.

 1 #include<iostream>
 2  
 3 using namespace std;
 4  
 5 int main()
 6 {
 7    int *n = new int(10); // initialization with new()
 8    cout<<*n;
 9    getchar();
10    return 0;
11 }

  (2)new is an operator, while malloc() is a fucntion.

  (3)new returns exact data type, while malloc() returns void *.

  (4)Operator new throws an exception if there is not enough memory, malloc returns a NULL.

  (5)Operator new[] requires to specify the number of objects to allocate, malloc requires to specify the total number of bytes to allocate.

  (6) malloc() returns void *, which has to be explicitly cast to the desired type but new returns the proper type.

  (7) Operator new/new[] must be matched with operator delete/delete[] to deallocate memory, malloc() must be matched with free() to deallocate memory.

  (8) The new/delete couple does not have a realloc alternative that is available when malloc/free pair is used. realloc is used to resize the length of an array or a memory block dynamically.

  Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

  转载请注明:http://www.cnblogs.com/iloveyouforever/

  2013-11-26  09:56:08

原文地址:https://www.cnblogs.com/iloveyouforever/p/3442722.html