C + + supplements--malloc free vs. new Delete
Preface
In c we often use malloc and free to dynamically allocate and release memory, which corresponds to new and delete in C + +. Here we are going to discuss their differences.
Body1. Built-in type
Debug the same code to see the memory
#include <iostream>using namespace Std;int main () {int *p = (int*) malloc (sizeof (int) *); cout << P << E ndl;//breakpoint for (int i = 0; i <; i++) P[i] = i;//breakpoint free (p);//breakpoint Cin.get (); return 0;}
Debugging
The same functionality uses new and delete to manipulate
#include <iostream>using namespace Std;int main () {int *p = new Int[10];cout << p << endl;<span style= "White-space:pre" ></span>//breakpoint for (int i = 0; i < i++) P[i] = I;<span style= "White-space:pre" ></sp an>//breakpoint Delete[]p;<span style= "White-space:pre" ></span>//breakpoint Cin.get (); return 0;}
Mode
For built-in types, the effect is the same for both sets of operations.
2. Class TypeCode One
#include <iostream>using namespace Std;class myclass{public:myclass () {cout << "MyClass create" << Endl;} ~myclass () {cout << "MyClass delete" << Endl;}}; int main () {MyClass *P1 = (MyClass *) malloc (sizeof (MyClass)), free (p1), cout << "--------------------" << Endl ; MyClass *p2 = new Myclass;delete p2;cin.get (); return 0;}
Run
malloc allocates only memory, and new does not only allocate memory, but also calls constructors.
Free simply frees up memory, and delete not only frees up memory, but also calls destructors.
Codetwo
#include <iostream> #include <new>using namespace Std;class myclass{public:int *p; MyClass () {//allocate 400M memory P = new int[1024 * 1024x768 * 100];cout << "MyClass create" << Endl;} ~myclass () {delete[]p;cout << "MyClass delete" << Endl;}}; int main () {MyClass *P1 = (MyClass *) malloc (sizeof (MyClass));//Breakpoint Free (p1);//breakpoint MyClass *P2 = new myclass;//Breakpoint Delete p2;// Breakpoint Cin.get (); return 0;}
start Task Manager to view memory consumption
malloc free
New Delete
Because malloc allocates memory only to the variable p itself, the p cannot be directed to a piece of allocated memory because the constructor is not called. Similarly, free simply frees the variable p and cannot free the memory that P points to because it does not call the destructor.
Directory of this column
- C + + Supplements directory
Directory of all content
C + + supplements--malloc free vs. new Delete