1. malloc and free are standard library functions of C ++/C, and new/delete are operators of C ++. They can be used to apply for dynamic memory and release memory.
2. For non-Internal data objects, the use of 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. Because malloc/free is a library function rather than an operator, it is not controlled by the compiler and cannot impose the tasks of executing constructor and destructor on malloc/free.
3. Therefore, the C ++ language requires a new operator that can complete dynamic memory allocation and initialization, and a delete operator that can clean up and release memory. Note that new/delete is not a database function.
4. c ++ programs often call C functions, while C Programs can only use malloc/free to manage dynamic memory.
5. New can be considered as the execution of the malloc and constructor. The new pointer directly carries the type information. Malloc returns the void * pointer.
The implementation of new Delete actually calls the malloc and free functions.
6. you can use a new object as a common object to access it using a member function instead of directly accessing its address space. malloc allocates a memory area, you can use the pointer and move the pointer in it.
7. New creates an object. alloc allocates a piece of memory.
***************************************
Similarities: both apply for dynamic memory and release memory
Differences:
(1) The operation objects are different.
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) The 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 ".
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.
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 needs to manually calculate 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, or even allocate it to non-memory devices. Malloc is powerless.
4 New will call constructor, but malloc cannot; Delete will call destructor, but free cannot.
5 malloc/free requires support for database files, while new/delete does not.
//---------------------------------------------------------
1. malloc and free are standard library functions of C ++/C, and new/delete are operators of C ++. They can be used to apply for dynamic memory and release memory.
2. For non-Internal data objects, the use of 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 and is not controlled by the compiler, it is impossible to impose the tasks of executing constructor and destructor on malloc/free.
3. Therefore, the C ++ language requires a new operator that can complete dynamic memory allocation and initialization, and a delete operator that can clean up and release memory. Note that new/delete is not a database function.
4. c ++ programs often call C functions, while C Programs can only use malloc/free to manage dynamic memory. New is an operator, and what "+ ","-", "= "... there is a similar position: malloc, free is the c function, new, delete is the c ++ operator, in addition, new is the force type, malloc is not, there are also many different types of conversions, of course. New constructors can call the Class Object Function to initialize malloc only to allocate space when declared. Initialization is required elsewhere, and delete not only releases space, the Destructor will be called before release, and malloc needs to specify the size of the allocated space, while new is automatically calculated.
Highlights of differences between new and malloc
1. New is the operator in C ++, and malloc is a function in C.
2. New not only allocates memory, but also calls class constructor. Similarly, delete calls class destructor, while malloc only allocates memory, does not initialize class members, or free does not call destructor.
3. Memory leakage can be checked out for malloc or new. The difference is that new can indicate the row of the file, but malloc does not have this information.
4. Comparison of new and malloc Efficiency
New has three letters, malloc has six letters
New can be considered as the execution of the malloc and constructor.
The new pointer directly carries the type information.
Malloc returns the void pointer.
1. New Delete is an operator, malloc and free are functions.
Malloc and free are standard library functions in C ++/C, and new/delete are operators in C ++. They can be used to apply for dynamic memory and release memory.
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. Because 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 numbers and destructor on malloc/free.
Therefore, the C ++ language requires a new operator that can complete dynamic memory allocation and initialization, and a delete operator that can complete the cleaning and release of memory. Note that new/delete is not a database function.
Let's first take a look at how malloc/free and new/delete implement dynamic memory management of objects, as shown in the example.
Class OBJ
{
Public:
OBJ (void) {cout <"initialization" <Endl ;}
~ OBJ (void) {cout <"Destroy" <Endl ;}
Void initialize (void) {cout <"initialization" <Endl ;}
Void destroy (void) {cout <"Destroy" <Endl ;}
};
Void usemallocfree (void)
{
OBJ * A = (OBJ *) malloc (sizeof (OBJ); // apply for dynamic memory
A-> initialize (); // Initialization
//...
A-> destroy (); // clear the job
Free (a); // releases the memory.
}
Void usenewdelete (void)
{
OBJ * A = new OBJ; // apply for dynamic memory and initialize
//...
Delete A; // clear and release the memory
}
How to Use malloc/free and new/Delete to manage the dynamic memory of Objects
The class OBJ function initialize simulates the constructor function, and the function destroy simulates the functions of the destructor. In usemallocfree, because malloc/free cannot execute constructor and destructor, you must call the member functions initialize and destroy to complete initialization and clearing. The usenewdelete function is much simpler.
Therefore, we should not attempt to 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.
Since the new/delete function completely covers malloc/free, why does C ++ not eliminate malloc/free? This is because C ++ programs often call C functions, and 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. For example, 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 must be paired, and the same applies to malloc/free.
Ii. New Delete actually calls the malloc and free functions in implementation.
3. In addition to memory allocation, new operator also calls constructors.
The malloc function is only responsible for allocating memory.
///////////////////////////////////////
New one-dimensional array
Xxx * arr;
Int Len; // dynamically determine the length value
Arr = new XXX [Len]; // Dynamic Allocation. You can also use malloc
...
Delete [] arr; // do not forget to release
New multi-dimensional array
The correct method is to declare an n-dimensional array. Each unit is a pointer to a char, and then allocate memory to each unit. The Code is as follows:
Char ** array = new char * [N];
For (INT I = 0; I array [I] = new char [m];
Note: pay special attention to the above Code when releasing the allocated memory. Because this is a "deep memory allocation", you need to release the memory pointed to by the pointer in each unit during release. The code for releasing memory is as follows:
For (I = 0; I delete [] array [I];
Delete [] array;
Malloc Function
Prototype: extern void * malloc (unsigned int num_bytes );
Usage: # include <malloc. h>
Function: allocate memory blocks of num_bytes bytes.
Note: If the allocation is successful, the pointer pointing to the allocated memory is returned. Otherwise, the NULL pointer is returned.
When the memory is no longer used, use the free () function to release the memory block.
The essence of the malloc function is that it connects available memory blocks into a long list of so-called idle linked lists. When calling the malloc function, it searches for a memory block that is large enough to meet user requests along the connection table. The memory block is then split into two parts (the size of one part is equal to the size of the user request, and the size of the other part is the remaining bytes ). Next, pass the memory allocated to the user, and return the remaining (if any) to the connection table. When the free function is called, it connects the memory block released by the user to the idle chain. At the end, the idle link will be cut into many small memory segments. If you apply for a large memory segment, there may be no fragments on the idle link that meet your requirements. Therefore, the request latency of the malloc function starts to rummaging through the idle chain to check the memory segments, sort them, and merge adjacent small idle blocks into larger memory blocks. If you cannot obtain a memory block that meets the requirements, the malloc function returns a null pointer. Therefore, when calling malloc to dynamically apply for a memory block, you must determine the return value.
Example:
// Malloc. c
# Include <syslib. h>
# Include <malloc. h>
Main ()
{
Char * P;
Clrscr (); // clear screen
P = (char *) malloc (100 );
If (P)
Printf ("memory allocated at: % x", P );
Else
Printf ("not enough memory! \ N ");
Free (P );
Getchar ();
Return 0;
}
Function declaration (function prototype ):
Void * malloc (INT size );
Description: malloc applies to the system for allocating a specified size of bytes of memory. The return type is void. Void * Indicates a pointer of unknown type. C, C ++ stipulates that the void * type can be forcibly converted to any other type of pointer.
We can see from the function declaration. There are at least two differences between malloc and new: New returns a pointer of the specified type and can automatically calculate the required size. For example:
Int * P;
P = new int; // The return type is int * (integer pointer) and the allocated size is sizeof (INT );
Or:
Int * Parr;
Parr = new int [100]; // The returned type is int * (integer pointer) and the allocated size is sizeof (INT) * 100;
While malloc must be calculated by the number of bytes and forcibly converted to the actual type of pointer after the return.
Int * P;
P = (int *) malloc (sizeof (INT ));
First, the malloc function returns the void * type. If you write it as P = malloc (sizeof (INT), the program cannot be compiled and an error is returned: "You cannot assign void * to int * type variables ". Therefore, you must use (int *) to forcibly convert the data.
Second, the real parameter of the function is sizeof (INT), used to specify the size required for an integer data. If you write:
Int * P = (int *) malloc (1 );
The code can also be compiled, but in fact only one byte memory space is allocated. When you store an integer in it, three bytes will be left homeless, and you can directly "Live in the neighbor's house "! The result is that all the original data in the memory is cleared.
Malloc can also achieve the effect of new [], and apply for a continuous memory, the method is nothing more than specify the memory size you need.
For example, you want to allocate 100 int-type space:
Int * P = (int *) malloc (sizeof (INT) * 100); // allocate memory space that can be placed in the next 100 integers.
Another difference that cannot be seen directly is that malloc only allocates memory and Cannot initialize the obtained memory. Therefore, the value of a new memory will be random.
In addition to the allocation and final release methods, you can use malloc or new to obtain pointers, Which are consistent in other operations.
Add a special case to it
Char * PTR;
If (PTR = (char *) malloc (0) = NULL)
Puts ("got a null pointer ");
Else
Puts ("got a valid Pointer ");
In this case, got a valid pointer is obtained. Assign 0 to maclloc to obtain a valid pointer.
Struct hostent * HP;
// Note that sizeof (sturct hostent) is not sizeof (sturct hostent *)
// N indicates the number of sturct hostent data you need.
HP = (struct hostent *) malloc (N * sizeof (sturct hostent ));
If (! HP) // we recommend that you check whether the memory allocation is successful or not.
{
// Processing Method for memory allocation failure
}
New Delete, free malloc
First, we should know that malloc and free match each other. New and delete match each other and they cannot be confused.
Both malloc and new apply for space. However, new is a strongly-typed allocation and calls the object's constructor to initialize the object. malloc only allocates memory space but does not initialize the object.
New Adaptive type. malloc needs to be forcibly converted to new for allocation by type. malloc needs to specify the memory size. For objects, free indeed releases the object's memory, but does not call the object's destructor. Delete not only releases the object's memory, but also calls the object's destructor. Therefore, if you use free to delete the new object in the object, the memory may leak and still call free in the delete object.
Note: Although both new and malloc apply for memory, the applied locations are different. The new memory is allocated from the free store, the memory of malloc is allocated from heap (For details, refer to the memory management section of). The free store and heap are very similar and both are dynamic memory, but their locations are different, this is why the new memory cannot be released through free. However, the Microsoft compiler does not have good execution standards and may confuse free store with heap. Therefore, free can be used sometimes.
Additionally, you do not need to check for null during the delete operation.
Delete NULL; there is no problem, so
If (P)
{
Delete P;
P = NULL;
}
Not as good
Delete P;
P = NULL;
Free (null) is too much trouble.
1. malloc and free are standard library functions of C ++/C, and new/delete are operators of C ++. They can be used to apply for dynamic memory and release memory.
2. For non-Internal data objects, you can use the maloc/Free Method to 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 and is not controlled by the compiler, it is impossible to impose the tasks of executing constructor and destructor on malloc/free.
3. c ++ language requires a new operator that can complete dynamic memory allocation and initialization, and a delete operator that can clean up and release memory. Note that new/delete is not a database function.
Let's take a look at how malloc/free and new/delete implement dynamic memory management for objects. See example 7-8.
Class OBJ
{
Public:
OBJ (void) {cout <"initialization" <Endl ;}
~ OBJ (void) {cout <"Destroy" <Endl ;}
Void initialize (void) {cout <"initialization" <Endl ;}
Void destroy (void) {cout <"Destroy" <Endl ;}
};
Void usemallocfree (void)
{OBJ * A = (OBJ *) malloc (sizeof (OBJ); // apply for dynamic memory
A-> initialize (); // Initialization
//... A-> destroy (); // clear the job
Free (a); // releases the memory.
}
Void usenewdelete (void)
{
OBJ * A = new OBJ; // apply for dynamic memory and initialize
//... Delete a; // clear and release the memory
}
Example 7-8 How to Use malloc/free and new/Delete to manage dynamic memory of Objects
The initialize function of the OBJ class simulates the constructor function, and the destroy function simulates the destructor function. In usemallocfree, because malloc/free cannot execute constructor and destructor, you must call the member functions initialize and destroy to complete initialization and clearing. The usenewdelete function is much simpler.
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.
4. Since the new/delete function completely covers malloc/free, why does C ++ not eliminate malloc/free? This is because C ++ calls C functions frequently, and 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 must be paired, and the same applies to malloc/free.
5. Usage of New:
Int * P = new int; // open an int variable in the free storage area.
Int * P = new int [10]; // open an int array in the free storage area with 10 elements
Int * P = new int (10); // open an int variable in the free storage area and initialize it as 10
[Reprinted] malloc and new