C++: The difference between new and malloc

1. Properties

new/delete is an operator, a C++ keyword, and needs compiler support; malloc/free is a library function and needs header file support.

2. Parameters

When using the new operator to dynamically allocate memory, you do not need to specify the size of the memory block, the compiler will calculate it according to the type; when malloc allocates memory, you need to explicitly indicate the required memory block size.

3. Return type

When the memory allocation of the new operator is successful, it will return the pointer of the corresponding object type, and no forced type conversion is required, which is in line with type safety. When the allocation fails, a bac_alloc exception will be thrown; when the malloc allocates memory successfully, it will return a pointer of type void*, which needs to be passed through Cast to the desired type, or return NULL on assignment failure.

4. Non-Internal Data Objects

new will call the operator new function first, apply for enough memory, then call the type's constructor, initialize member variables, and finally return the pointer of the custom type; delete will first call the destructor, and then call the operator delete function to release the memory; malloc/ free is a library function, which can only dynamically apply for memory and release memory, but cannot complete the work of constructor and destructor.

5. Overload

C++ allows overloading new/delete (actually overloading operator new and operator delete). In particular, layout new (placement new) does not need to allocate memory for the object, but uses a specified address as the memory starting area, new Complete the object's constructor call on this memory segment and initialize the memory segment, and return this memory address; malloc/free does not allow overloading.

6. Memory area

The new operator dynamically allocates space for objects from free stone, and the malloc function dynamically allocates memory from the heap. The free storage area is an abstract concept based on the new operator in C++. Whenever a memory application is made through the new operator, the memory is a free storage area; the heap is the corresponding memory area allocated in the operating system. The free storage area is not equal to the heap, and the layout new does not need to be in the heap. The heap is an actual area, while the free memory area is a higher-level concept. Usually new does apply for memory on the heap, but programmers can overload the new operator and use other memory to achieve free storage (uncommon). In addition, the layout new mentioned in the book C++primer plus, Objects can be allocated memory on the stack. In general, the free storage area is the concept of the interval of the new application.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325846915&siteId=291194637