The difference between the standard library function Malloc/free and operator New/delete in C + + language

Source: Internet
Author: User

in a nutshell.
1. malloc and free are C++/C standard library functions, and New/delete are C + + operators that can be used to request dynamic memory and release memory. 2, for non-internal data types of objects, only with Malloc/free can not meet the requirements of dynamic objects. When an object is created, the constructor is automatically executed, and the object executes the destructor automatically before it dies. The task of executing constructors and destructors cannot be imposed on Malloc/free because Malloc/free is a library function and not an operator, not within the control of the compiler. 3. Therefore, the C + + language requires an operator new that can perform dynamic memory allocation and initialization, and an operator delete that can perform cleanup and release of memory work. Note that New/delete is not a library function, but an operator. 4, new can be considered as malloc plus the execution of constructors. The new pointer is directly with the type information. and malloc returns a void pointer. 5, C + + programs often call C functions, and C programs can only use Malloc/free to manage dynamic memory.
In detailmalloc and free are standard library functions for c++/c languages, and new/delete are operators of C + +. They can all be used to request dynamic memory and free memory. Here's a look at their differences. one, the object of operation is differentmalloc and free are standard library functions for c++/c languages, and new/delete are operators of C + +.    For objects of non-intrinsic data types, light Malloc/free cannot meet the requirements of dynamic objects. Objects are automatically executed when they are created, and the destructor is executed automatically before the object 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 compiler's control permissions.An operator is an attribute of the language itself, it has a fixed semantics, and the compiler knows what it means. Just like +-*/, the compiler interprets the semantics and generates the corresponding code. Library functions are library-dependent, without which there is no library, which is partly language-independent. In theory, the compiler does not know or care about the function, the compiler guarantees only the compiler function, and the code that calls the function when the parameter and return values conform to the syntax, and generates the corresponding call function. But in fact, some of the higher-level compilers will take special care of some of the functions that the standard library comes with. second, in the use of different① function mallocOf prototypesas follows: void * malloc (size_t size);

Use malloc to request a block length integer type of memory, the program is as follows:

Int*p = (int *) malloc (sizeof (int) * length);

We should focus on two elements: "Type conversion" and "sizeof".

1, the type of malloc return value is void *, so when you call malloc to explicitly type-convert, the void * is converted to the desired pointer type. 2. The Mallo function itself does not recognize what type of memory to apply, it only cares about the total number of bytes in memory。 Function FreeThe prototype is as follows: voidFree ( void * memblock );

Why is the free function not as complex as the malloc function? This is because the type of the pointer p and the amount of memory it refers to is known beforehand, and the statement free (p) frees the 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 .

② Key points of use of New/delete

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 new creates an array of objects, then only the parameterless constructor of the object can be used. For example:
    1. OBJ *objects = new obj[100]; Create 100 Dynamic objects
Cannot be written
When releasing an array of objects with Delete, ★ Be careful not to lose the symbol ' [] '. For example, obj*objects = new obj[100] (1);// Create An initial value of 1 for each dynamic object
    • delete []objects; The right usage
    • Delete objects; Incorrect use of

The latter is equivalent to delete objects[0], missing another 99 objects.

New and malloc differences ★

1. New automatically calculate the space you need to allocate, and malloc needs to manually calculate the number of bytes
2. New is type safety, and malloc is not, for example:
    • int* p = new Float[2]; Errors are indicated at compile time
    • int* p = malloc (2*sizeof (float)); Cannot indicate error at compile time
New operator is made up of two steps, operator new and CONSTRUCT3, operator new, which correspond to malloc, but operator new can be overloaded, you can customize the memory allocation policy, and even do not allocate memory. Even if it is assigned to a non-memory setting, and malloc is powerless 4, new will call the constructor constructor, and malloc cannot; the delete will call the destructor destructor, and free cannot. 5, Malloc/free to the library file support, New/delete do not. Essential DifferencesMalloc/free is a standard library function for the C + + language, and New/delete is an operator of C + +. For user-defined objects, Malloc/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. Therefore, C + + requires an operator new that can perform dynamic memory allocation and initialization, and an operator delete that can perform cleanup and freeing of memory work.

1 classOBJ2 {3  Public :4OBJ () {cout << ' initialization ' <<Endl;}5~ Obj () {cout << "Destroy" <<Endl;}6     voidInitialize () {cout << "initialization" <<Endl;}7     voidDestroy () {cout << "Destroy" <<Endl;}8 };9 voidUsemallocfree ()Ten { Oneobj * a = (obj *)malloc(sizeof(obj));//Allocate Memory AA-Initialize ();//initialization -     //... .. -A-Destroy ();//Deconstruction the      Free(a);//Release Memory - } - voidUsenewdelete (void ) - { +OBJ * a =NewOBJ; -     //... .. +     DeleteA; A}

The code interprets the function of the class obj initialize implements the function of the constructor, 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.
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 function, and C programs 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,malloc/free must pairing with。 Reference: http://blog.sina.com.cn/s/blog_6371284401012pqf.html

The difference between the standard library function Malloc/free and operator New/delete in C + + language

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.