in a C + + program Ape interview. Very easy to be asked about the difference between new and malloc. Occasionally strolling on the Quora. See
a summary of Robert Love. Only to find that they only know the one or two items on the complacent, never like this Daniel to think carefully about these issues, through this article carefully discuss the classic problem.
first, new is the operator. And malloc is a function
void* malloc (size_t); void free (void*);
void *operator New (size_t), void operator delete (void *), void *operator new[] (size_t); void operator delete[] (void *);
Second, new allocates memory at the time of invocation, and the constructor is called. The destructor is called when it is released.
#include <iostream>using namespace Std;class player{public: Player () { cout << ' Call player::ctor\ n "; } ~player () { cout << "Call Player::d tor\n"; } void Log () { cout << "I am player\n"; }}; int main () { cout << "Initiate by new\n"; player* P1 = new Player (); P1->log (); Delete P1; cout << "Initiate by malloc\n"; player* P2 = (player*) malloc (sizeof (Player)); P2->log (); Free (p2);}
The output is:
Initiate by new
Call Player::ctor
I am player
Call Player::d Tor
Initiate by malloc
I am player
Third, new is type-safe, and malloc returns to void*
Iv. New can be overloaded
v. New allocation of memory more direct and secure
vi. malloc can be realloc
#include <iostream>using namespace Std;int main () { char* str = (char*) malloc (sizeof (char*) * 6); strcpy (str, "Hello"); cout << str << endl; str = (char*) realloc (str, sizeof (char*) *); strcat (str, ", World"); cout << str << endl; Free (str);}
The output is:
Hello
Hello,world
Seven, the new error occurred throwing an exception. malloc returns null
malloc can allocate random bytes, and new can only allocate integer multiples of the memory occupied by the instance
Conclusion:
Learning knowledge when the assumption can grasp the development of the entire technology history and context, so that some of the more difficult to understand the knowledge is very easy to understand.
Put these technologies in their own time, taking into account the hardware and software environment. To better understand the technology itself.
This article is very shallow to illustrate their differences. Suppose to be interested in being able to study their detailed implementation. can find greater pleasure.
C + + 's new and malloc differences