Baidu written question: The difference between Malloc/free and New/delete

Source: Internet
Author: User

Baidu written question: The difference between Malloc/free and New/delete

Same point: Both can request dynamic memory and free memory.

Different points:

(1) The operating objects are different:

malloc and free are standard library functions for C/s + +, and new and delete are operators of C + +. For objects that are not internal data classes, light Malloc/free cannot satisfy the requirements of dynamic objects. Objects are automatically executed when they are created, the destructor is automatically executed before the object dies, and malloc and free are library functions rather than operators, not within the control of the compiler, and cannot be imposed on Malloc/free for the task of executing constructors and destructors.

(2) The usage is also different:

The

function malloc is prototyped as follows:
void * malloc (size_t size); The
uses malloc to request a piece of memory of length long integer type, the program is as follows:
int *p = (int *) malloc (sizeof (int) * length);
We should focus on two elements: "Type conversion" and "sizeof".
1, malloc return value is void *, so type conversion is performed explicitly when malloc is called, converting void * to the desired pointer type .
2,  malloc function itself does not recognize what type of memory to request , it only cares about the total number of bytes in memory . The
function free is prototyped as follows:
void free (void * memblock);
      Why is the free function not as complex as the malloc function? This is because , and the statement free (p) frees memory correctly. If p is a null pointer, then free has no problem with P no matter how many times it is manipulated. If p is not a null pointer, then the free operation of P for two consecutive times causes the program to run incorrectly.

New/delete Points of Use:
Operator new is much simpler to use than the function malloc, for example:
int *P1 = (int *) malloc (sizeof (int) * length);
int *p2 = new Int[length];
This is because new has built-in sizeof, type conversion, and type safety check functionality. For objects that are not internal data types, new initializes the initialization work while creating the dynamic object. If an object has more than one constructor, the new statement can also have multiple forms.
If you create an array of objects with new, you can only use the parameterless constructor of the object. For example
OBJ *objects = new obj[100]; Create 100 Dynamic objects
Cannot be written
OBJ *objects = new obj[100] (1); Create 100 dynamic objects while assigning the initial value 1
When releasing an array of objects with delete, be careful not to lose the symbol ' [] '. For example
delete []objects; The right usage
Delete objects; Incorrect use of
The latter is equivalent to delete objects[0], missing another 99 objects.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////

1. New automatically calculates the space that needs to be allocated , and malloc needs to manually calculate the number of bytes
2.new is type-safe, and malloc is notLike what:
int* p = new Float[2]; Errors are indicated at compile time
int* p = malloc (2*sizeof (float)); Cannot indicate error at compile time
The new operator is made up of two steps, namely operator new and construct
3.operator new corresponds to malloc, but operator new can be overloaded, and you can customize the memory allocation policy without even allocating memory, even to non-memory devices. and malloc could do nothing.
4, new will call constructor, and malloc cannot; Delete will call destructor, and free cannot.
5.Malloc/free to library file support, New/delete do not.
/////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////

1. Essential Difference
Malloc/free is a standard library function for the C + + language, and New/delete is an operator of C + +.
For user-defined objects, Maloc/free cannot meet the requirements of dynamic management objects. Objects are automatically executed when they are created, and the object executes the destructor automatically before it dies. Because Malloc/free is a library function and not an operator, the task of executing constructors and destructors cannot be imposed on malloc/free, not within the control of the compiler. C + + therefore requires an operator new that can perform dynamic memory allocation and initialization, and an operator delete that cleans up and frees up memory work.

classobj{ Public: Obj () {cout<<"initialization"<<Endl;} ~Obj () {cout<<"Destroy"<<Endl;} voidInitialize () {cout<<"initialization"<<Endl;} voidDestroy () {cout<<"Destroy"<<Endl;}} obj;voidUsemallocfree () {OBJ* A = (OBJ *) malloc (sizeof(obj));//Allocate MemoryA-Initialize ();//initialization//... ..A-Destroy ();//DeconstructionFree (a);//Release Memory}voidUsenewdelete (void) {OBJ* A =NewOBJ; //... ..delete A;}

The function of the class obj initialize realizes the function of the constructor function, and the function destroy realizes the function of the destructor. In function Usemallocfree, because Malloc/free cannot execute constructors and destructors, member functions initialize and destroy must be called to complete the construction and destruction. So we do not use Malloc/free to complete dynamic object memory management, should use New/delete. Because the "objects" of the internal data types do not have a process of construction and destruction, Malloc/free and new/delete are equivalent to them.

2. Contact
Since New/delete's functionality completely covers the Malloc/free, why is C + + still reserved for malloc/free? Because C + + programs often have to call C functions, the program can only use Malloc/free to manage dynamic memory. If you release the dynamic object created by new with free, the object can cause a program error because it cannot execute the destructor. If you release "Dynamic Memory for malloc request" with delete, the program is theoretically not error-free, but the program is poorly readable. so new/delete and Malloc/free must be paired with each other.

Baidu written question: The difference between Malloc/free and New/delete (turn)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.