Difference between malloc/free and new/delete

Source: Internet
Author: User
Similarities: Can be used to apply for dynamic memory and release memory

Differences:
(1)Different operation objects.
Malloc and free are standard library functions in C ++/C, and new/delete are operators in C ++. For non-Internal data objects, maloc/free alone cannot meet the requirements of dynamic objects. The constructor must be automatically executed when the object is created, and the Destructor must be automatically executed before the object is extinct. Since malloc/free is a library function rather than an operator, it is not controlled by the compiler and cannot impose malloc/free on tasks that execute constructors and destructor.

(2) usage is also different.
The following is a prototype of the malloc function:
Void * malloc (size_t size );
Use malloc to apply for an integer-type memory with a length. 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 returned by malloc is void *. Therefore, you must explicitly convert the type when calling malloc and convert void * to the required pointer type.
2. the malloc function does not recognize the type of memory to be applied for. It only cares about the total number of bytes in the memory.
The prototype of function free is as follows:
Void free (void * memblock );
Why isn't the free function as complicated as the malloc function? This is because the pointer p type and the memory capacity it refers to are known in advance, and the statement free (p) can correctly release the memory. If P is a null pointer, then free
P is normal no matter how many operations are performed. If P is not a null pointer, the free operation on P will cause a program running error.

Usage of new/delete:
The new operator is much easier to use than the malloc function, 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 security check functions. For non-Internal data objects, new completes initialization while creating dynamic objects. If an object has multiple constructors, the new statement can also have multiple forms.
If you use new to create an object array, you can only use the non-parameter 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 and assign initial value 1
When releasing an object Array Using Delete, do not lose the symbol '[]'. For example
Delete [] objects; // correct usage
Delete objects; // incorrect usage
The latter is equivalent to delete objects [0], and 99 Other objects are missing.
//////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// /////////////////////////////////////

1. new automatically calculates the space to be allocated, while malloc manually calculates the number of bytes.
2. new is type-safe, but malloc is not. For example:
Int * p = new float [2]; // indicates an error during compilation
Int * p = malloc (2 * sizeof (float); // The error cannot be specified during compilation.
New operator consists of two steps: operator new and construct
3. operator new corresponds to malloc, but operator new can be reloaded. You can customize memory allocation policies, or even do not allocate memory to non-memory devices. Malloc is powerless.
4. new will call constructor, but malloc will not; delete will call destructor, but free will not.
5. malloc/free must be supported by the library file, but not new/delete.
//////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// /////

1. Essential differences
Malloc/free is a standard library function in C/C ++, and new/delete is a C ++ operator.
For custom objects, the use of maloc/free cannot meet the requirements of Dynamic Object Management. The constructor must be automatically executed when the object is created, and the Destructor must be automatically executed before the object is extinct. Since malloc/free is a library function rather than an operator and is not controlled by the compiler, it is impossible to impose the tasks of executing constructor and destructor on malloc/free. Therefore, C ++ needs a new operator that can complete dynamic memory allocation and initialization, and a delete operator that can clean up and release memory.

[Cpp]
View plaincopyprint?
  1. Class Obj
  2. {
  3. Public:
  4. Obj ()
  5. {Cout <"Initialization" <endl ;}
  6. ~ Obj ()
  7. {Cout <"Destroy" <endl ;}
  8. Void initialize ()
  9. {Cout <"initialization" <Endl ;}
  10. Void destroy ()
  11. {Cout <"Destroy" <Endl ;}
  12. } OBJ;
  13. Void usemallocfree ()
  14. {
  15. OBJ * A = (OBJ *) malloc (sizeof (OBJ); // allocate memory
  16. A-> Initialize (); // initialization
  17. //...
  18. A-> Destroy (); // deconstruction
  19. Free (a); // release memory
  20. }
  21. Void UseNewDelete (void)
  22. {
  23. Obj * a = new Obj;
  24. //...
  25. Delete;
  26. }
class Obj{public:Obj( ) { cout  <<  "Initialization"  <<  endl; }~ Obj( ){ cout  <<  "Destroy" <<  endl; }void Initialize( ){ cout  <<  "Initialization"  <<  endl; }void  Destroy( ){ cout  <<  "Destroy"  <<  endl; }}obj;void  UseMallocFree( ){Obj   * a  =  (Obj  *) malloc( sizeof ( obj ) );      //  allocate memory a -> Initialize();                                    //  initialization// … a -> Destroy();                                        // deconstruction free(a);                                               // release memory}void  UseNewDelete( void ){Obj   * a  =   new  Obj;                                           // … delete a; }

The class Obj function Initialize implements the constructor function, and the function Destroy implements the destructor function. In UseMallocFree, because malloc/free cannot execute constructor and destructor, you must call the member functions Initialize and Destroy to complete the "constructor" and "destructor ". Therefore, we should not use malloc/free to manage the memory of dynamic objects. We should use new/delete. Because the internal data type "object" does not have a process of construction and analysis, malloc/free and new/delete are equivalent to them.

2. Contact
Since the new/delete function completely covers malloc/free, why does C ++ retain malloc/free? C ++ programs often call C functions, while C Programs can only use malloc/free to manage dynamic memory. If you use free to release the "New Dynamic Object", this object may cause program errors because it cannot execute the destructor. If you use Delete to release the "dynamic memory applied by malloc", theoretically, the program will not go wrong, but the program is poorly readable. Therefore, new/delete and malloc/free must be paired.

Similarities: Can be used to apply for dynamic memory and release memory

Differences:
(1)Different operation objects.
Malloc and free are standard library functions in C ++/C, and new/delete are operators in C ++. For non-Internal data objects, maloc/free alone cannot meet the requirements of dynamic objects. The constructor must be automatically executed when the object is created, and the Destructor must be automatically executed before the object is extinct. Since malloc/free is a library function rather than an operator, it is not controlled by the compiler and cannot impose malloc/free on tasks that execute constructors and destructor.

(2) usage is also different.
The following is a prototype of the malloc function:
Void * malloc (size_t size );
Use malloc to apply for an integer-type memory with a length. 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 returned by malloc is void *. Therefore, you must explicitly convert the type when calling malloc and convert void * to the required pointer type.
2. the malloc function does not recognize the type of memory to be applied for. It only cares about the total number of bytes in the memory.
The prototype of function free is as follows:
Void free (void * memblock );
Why isn't the free function as complicated as the malloc function? This is because the pointer p type and the memory capacity it refers to are known in advance, and the statement free (p) can correctly release the memory. If P is a null pointer, then free
P is normal no matter how many operations are performed. If P is not a null pointer, the free operation on P will cause a program running error.

Usage of new/delete:
The new operator is much easier to use than the malloc function, 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 security check functions. For non-Internal data objects, new completes initialization while creating dynamic objects. If an object has multiple constructors, the new statement can also have multiple forms.
If you use new to create an object array, you can only use the non-parameter 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 and assign initial value 1
When releasing an object Array Using Delete, do not lose the symbol '[]'. For example
Delete [] objects; // correct usage
Delete objects; // incorrect usage
The latter is equivalent to delete objects [0], and 99 Other objects are missing.
//////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// /////////////////////////////////////

1. new automatically calculates the space to be allocated, while malloc manually calculates the number of bytes.
2. new is type-safe, but malloc is not. For example:
Int * p = new float [2]; // indicates an error during compilation
Int * p = malloc (2 * sizeof (float); // The error cannot be specified during compilation.
New operator consists of two steps: operator new and construct
3. operator new corresponds to malloc, but operator new can be reloaded. You can customize memory allocation policies, or even do not allocate memory to non-memory devices. Malloc is powerless.
4. new will call constructor, but malloc will not; delete will call destructor, but free will not.
5. malloc/free must be supported by the library file, but not new/Delete.
//////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// //////////////////////////////////////// /////

1. Essential differences
Malloc/free is a standard library function in C/C ++, and new/delete is a C ++ operator.
For custom objects, the use of maloc/free cannot meet the requirements of Dynamic Object Management. The constructor must be automatically executed when the object is created, and the Destructor must be automatically executed before the object is extinct. Since malloc/free is a library function rather than an operator and is not controlled by the compiler, it is impossible to impose the tasks of executing constructor and destructor on malloc/free. Therefore, C ++ needs a new operator that can complete dynamic memory allocation and initialization, and a delete operator that can clean up and release memory.

[CPP]
View plaincopyprint?
  1. Class Obj
  2. {
  3. Public:
  4. Obj ()
  5. {Cout <"Initialization" <endl ;}
  6. ~ Obj ()
  7. {Cout <"Destroy" <endl ;}
  8. Void Initialize ()
  9. {Cout <"Initialization" <endl ;}
  10. Void Destroy ()
  11. {Cout <"Destroy" <endl ;}
  12. } Obj;
  13. Void UseMallocFree ()
  14. {
  15. Obj * a = (Obj *) malloc (sizeof (obj); // allocate memory
  16. A-> Initialize (); // initialization
  17. //...
  18. A-> Destroy (); // deconstruction
  19. Free (a); // release memory
  20. }
  21. Void UseNewDelete (void)
  22. {
  23. Obj * a = new Obj;
  24. //...
  25. Delete;
  26. }
class Obj{public:Obj( ) { cout  <<  "Initialization"  <<  endl; }~ Obj( ){ cout  <<  "Destroy" <<  endl; }void Initialize( ){ cout  <<  "Initialization"  <<  endl; }void  Destroy( ){ cout  <<  "Destroy"  <<  endl; }}obj;void  UseMallocFree( ){Obj   * a  =  (Obj  *) malloc( sizeof ( obj ) );      //  allocate memory a -> Initialize();                                    //  initialization// … a -> Destroy();                                        // deconstruction free(a);                                               // release memory}void  UseNewDelete( void ){Obj   * a  =   new  Obj;                                           // … delete a; }

The class OBJ function initialize implements the constructor function, and the function destroy implements the destructor function. In usemallocfree, because malloc/free cannot execute constructor and destructor, you must call the member functions initialize and destroy to complete the "constructor" and "destructor ". Therefore, we should not use malloc/free to manage the memory of dynamic objects. We should use new/Delete. Because the internal data type "object" does not have a process of construction and analysis, malloc/free and new/delete are equivalent to them.

2. Contact
Since the new/delete function completely covers malloc/free, why does C ++ retain malloc/free? C ++ programs often call C functions, while C Programs can only use malloc/free to manage dynamic memory. If you use free to release the "new Dynamic Object", this object may cause program errors because it cannot execute the destructor. If you use delete to release the "dynamic memory applied by malloc", theoretically, the program will not go wrong, but the program is poorly readable. Therefore, new/delete and malloc/free must be paired.

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.