The difference between new and malloc

1. malloc and free are standard library functions of C++/ C language , and new/delete are operators of C++. Both of them can be used to allocate dynamic memory and free memory. 

2. For objects of non-internal data types, maloc/free alone cannot meet the requirements of dynamic objects. Objects automatically execute constructors when they are created, and destructors are automatically executed before objects die .
Since malloc/free is a library function rather than an operator, it is not within the control of the compiler, and the task of executing the constructor and destructor cannot be imposed on malloc/free.

3. Therefore, the C++ language needs an operator new that can complete the work of dynamic memory allocation and initialization , and an operator delete that can complete the work of cleaning up and releasing memory. Note that new/delete are not library functions .

4. C++ programs often call C functions , while C programs can only manage dynamic memory with malloc/free .

5. new can be considered as malloc plus constructorexecution. The new pointer is directly with type information. And malloc returns a void pointer.

One: new delete is an operator, malloc and free are functions

malloc and free are standard library functions of C++/ C language , and new/delete is an operator of C++. Both of them can be used to allocate dynamic memory and free memory.

For objects of non-internal data types, maloc/free alone cannot meet the requirements of dynamic objects. Objects automatically execute constructors when they are created, and destructors are automatically executed before objects die . Since malloc/free is a library function rather than an operator, it is not within the control of the compiler, and the task of executing the constructor and destructor cannot be imposed on malloc/free.

Therefore , the C++ language needs an operator new that can complete the work of dynamic memory allocation and initialization , and an operator delete that can complete the work of cleaning and freeing memory. Note that new/delete are not library functions.



Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324886559&siteId=291194637