Difference between new and malloc

Source: Internet
Author: User

1. malloc () function
1.1 The full name of malloc is memory allocation.
Prototype: extern void * malloc (unsigned int num_bytes );
Note: allocate memory blocks of num_bytes bytes. If the allocation is successful, the pointer pointing to the allocated memory is returned,If the allocation fails, null pointer is returned.. When the memory is no longer used, use the free () function to release the memory block.

1.2 void * malloc (INT size );
Description: malloc applies to the system for allocating a specified size of bytes of memory space. 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.
Note: void * Indicates a pointer of unknown type, more specifically, it means that when applying for a memory space, you do not know the type of data that the user uses to store (such as char, Int, or ...)

1.3 free
Void free (void * firstbyte): This function returns the space previously allocated with mallocProgramOr the operating system, that is, the memory is released to make it free again.

1.4 precautions
1) after applying for memory space,Check whether the allocation is successful.
2) when you no longer need to use the applied memory,Remember to release; after the release, point the pointer to this memory to null.To prevent the program from using it accidentally.
3) These two functions should be paired. If the application is not released, the memory is leaked. If the application is released without reason, nothing is done.Only one release is allowed. If two or more releases are released, an error occurs.(With the exception of releasing a null pointer, releasing a null pointer does not actually mean that nothing is done, so it is no problem to release a null pointer many times ).
4) Although the type of the malloc () function is (void *), pointers of any type can be converted to (void *), it is best to force type conversion before, this can avoid some compiler checks.

1.5 Where does malloc () Get the memory space?
The answer is to get space from the heap. That is to say, the pointer returned by the function points to a piece of memory in the heap. The operating system has a linked list that records idle memory addresses. When the operating system receives a program application, it traverses the linked list and searches for the first heap node with a larger space than the requested space, then, the node is deleted from the idle node linked list and the space of the node is allocated to the program.

2. New operator

2.1 C ++, use new and delete to dynamically create and release arrays orSingle Object.

When an object is dynamically created,You only need to specify the Data Type instead of naming the object., New expressionReturns the pointer to the newly created object., We canAccess this object through pointers.
Int * Pi = new int;
This new expression creates an integer object in the heap, returns the address of this object, and initializes the pointer PI with this address.

2.2 initialize the dynamically created object

Dynamically created objects can be initialized using initialization variables.
Int * Pi = new int (100); // The object pointed to by the pointer piInitializationIs 100
String * PS = new string (10, '9'); // * PS is "9999999999"

If no display Initialization is provided,For the class type,Default constructor InitializationAndBuilt-in objects are not initialized..
You can also perform value initialization for dynamically created objects:
Int * Pi = new int (); // Initialization is 0
Int * Pi = new int; // PI points to an uninitialized int
String * PS = new string (); // Initialization is a null string (for the class type that provides the default constructor, it is not necessary to initialize the value of its object)

2.3 undo dynamically created objects

The delete expression releases the address space pointed to by the pointer.
Delete PI; // release a single object
Delete [] PI; // release the Array
If the pointer points to a memory address not allocated by new, delete is invalid.

2.4 reset the pointer value after the delete operation

Delete P; // after the statement is executed, p becomes an uncertain pointer. On many machines, although the P value is not clearly defined, it still stores the address of the object it previously referred, then the memory pointed to by P has been released, so P is no longer valid. At this point, the pointer becomes a suspension pointer (the suspension Pointer Points to the memory of the previously stored object, but the object does not exist ). Hanging pointers often lead to program errors and are difficult to detect.
Once the object indicated by the pointer is deleted, the pointer is immediately set to 0.In this way, it is very clear that the pointer does not point to any object. (Zero pointer: int * IP = 0 ;)

2.5 distinguish between NULL pointer and NULL pointer

A zero-value pointer is a pointer with a value of 0. It can be any pointer type. It can be a common variant type void * or char * or int.
A null pointer is actually a programming concept. For example, a container may have two basic states: Empty and non-empty, and a value of 0 may be stored in a non-empty container, therefore, null pointers are artificially considered pointers that do not provide any address information. Reference: http://www.cnblogs.com/fly1988happy/archive/2012/04/16/2452021.html

2.6What is returned when the new allocation fails?

Before December 31, 1993, C ++ always asked operator newReturns 0.Now operator new is required.Throw an STD: bad_alloc exception.. Many C ++ programs are written before the compiler starts to support new specifications. The C ++ Standards Committee does not want to abandon those that have followed the return 0 specification.CodeSo they provide another form of operator new (and operator new []) to continue to provide the return 0 function. These forms are called "No throws" because they have never used a throw,The nothrow object is used at the entry point using new.:
Class widget {...};

Widget * pw1 = new widget; // if the allocation fails, STD: bad_alloc is thrown.

If (pw1 = 0)... // This check must fail.

Widget * pw2 = new (nothrow) widget; // if the allocation fails, 0 is returned.

If (pw2 = 0)... // This check may be successful

3. Differences between malloc and new

3.1New returns a pointer of the specified type and automatically calculates the required size.
For example:
1) 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;
2) whileMalloc requires us to calculate the number of bytes and forcibly convert it to a pointer of the actual type after the return.
Int * P;
P = (int *) malloc (sizeof (INT) * 128); // 128 storage units are allocated (this value can be replaced based on actual needs, and store the first address of the 128 consecutive integer storage units to the pointer Variable P.
Double * Pd = (double *) malloc (sizeof (double) * 12); // allocate 12 double storage units and store the first address in the pointer variable PD.

3.2Malloc only allocates memory and Cannot initialize the memory.,SoThe value of the 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.

4. Why New/delete?

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)Non-Internal data type objectsMaloc/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.
Therefore, the C ++ LanguageA new operator is required to complete dynamic memory allocation and initialization., AndA Delete operator that can clean up and release memory.Note that new/delete is not a database function.
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.
3) 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. If you use Delete to release the "dynamic memory requested by malloc", the results will also lead to program errors, but the program is poorly readable. Therefore, new/delete must be paired, and the same applies to malloc/free.

 

 

 

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.