In-depth understanding of C++ dynamic memory management: the difference and connection between malloc/free and new/delete

 malloc/free 和 new/delete

The same point: both can be used to apply for dynamic memory and release memory. All allocated memory is allocated on the heap.


Differences: 1. new/delete is a C++ operator, while malloc/free is a function in C.
                2. new does two things, one is to allocate memory, and the other is to call the constructor of the class; similarly, delete will call the destructor of the class and release the memory. Whereas malloc and free just allocate and free memory.
                3. New creates an object, while malloc allocates a piece of memory; the object created by new can be accessed with member functions, and do not directly access its address space; malloc allocates a memory area, which can be accessed by pointer Move the pointer; the pointer from new has type information, and malloc returns a void pointer.
                4. new/delete is a reserved word and does not require header file support; malloc/free requires header file library function support.


Contact: Since the functions of new/delete completely cover malloc/free, why does C++ still retain malloc/free? Because C++ programs often call C functions, and C programs can only manage dynamic memory with malloc/free. If the "dynamic object created by new" is released with free, then the object may cause a program memory leak error because the destructor cannot be executed. If you use delete to release the "dynamic memory requested by malloc", theoretically the program will not go wrong, but the readability of the program is very poor.

          So new/delete, malloc/free must be used in pairs.


Example:

class Array
{
	public :
	Array(size_t size = 10)
		: _size(size)
		, _a(0)
	{
		cout << "Array(size_t size)" << endl;
		if (_size > 0)
		{
			_a = new int[size];
		}
	} ~
		Array()
	{
		cout << "~Array()" << endl;
		if (_a)
		{
			delete[] _a;
			_a = 0;
			_size = 0;
		}
	}
private:
	int*_a;
	size_t _size;
};
void Test()
{
	Array* p1 = (Array*)malloc(sizeof (Array));
	Array* p2 = new Array; Array* p3 = new Array(20);
	Array* p4 = new Array[10];
	free(p1);
	delete p2;
	delete p3;
	delete[] p4;
}



Guess you like

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