First,Malloc/free
1.Malloc Prototypes:(#include <malloc.h>)
Void * malloc (size_t size); Void * malloc (unsigned int num_bytes);
Returns NULLif the allocation fails,otherwise returns the first address of the requested memory. malloc itself does not recognize the type of memory to be requested ( the return type is void *), only the number of bytes in memory , Therefore, the type conversion must be performed explicitly.
prototypes for 2.Free:
void free (void *memblock);
If free (p) isp==null, then no matter how many times the free operation is not error, if p!=null , then a continuous error of p free two times will occur.
Second,New/delete new[]/[]delete
New operator is composed of two steps,operator new and construct.
Delete operator is composed of two steps,operator delete and destroy.
Three, the same:
1. Both dynamic memory allocation and deallocation can be performed.
Both 2.free and Delete can release a NULL pointer. ?
Four, different:
1.malloc/free is a standard library function for the C + + language, andnew/delete is an operator of C + + .
Operator new corresponds to malloc, but Operator new can be overloaded, can customize memory allocation policies, or even be assigned to non-memory devices, but malloc cannot.
2.new can automatically allocate space, and malloc needs to calculate the number of bytes.
the New built-in sizeof, type conversion, and type safety check functionality.
3.New is type-safe, andmalloc is not.
Int *p=new float[2]// compilation Error
Int *p=malloc (sizeof (float));// compilation cannot indicate an error.
4. For objects of non-intrinsic data types, objects need to be automatically executed while they are created, and the object needs to perform the destructor automatically before it dies. New at the same time, the dynamic memory allocation and initialization of the object are completed. Delete at the same time, the work of cleaning and releasing memory is completed, while malloc and the Free not to.
A null pointer is returned when the 5.Malloc allocation fails.
Operator new assignment fails, throws a std::bad_alloc exception, but continues to provide functionality that returns 0 . However , the nothrow object is used in the entry point where new is used .
Student *stu=new (nothrow) student;// If allocation failed to return 0
If (stu==0)// the check may succeed.
6.Malloc is requesting the memory space for the heap , andnew is requesting the free store 's memory space.
V. Contact:
C + + also retains the malloc/free, since C + + often has to call the function . But it has to be used in a matching.
Malloc/free and New/delete