in C + + programmer interviews, it's easy to ask the difference between new and malloc. Occasionally strolling on the Quora, and seeing
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 explore the classic problem.
first, new is the operator, and malloc is the 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, calls the destructor when the constructor is called, and releases the function.
#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
Vii. New error throws an exception, malloc returns null
Viii. malloc can allocate arbitrary bytes, new can only allocate integer multiples of the memory occupied by the instance
Conclusion:
When learning knowledge, if you can grasp the development of the entire technology history and context, so that some more difficult to understand the knowledge is easy to understand. Put these technologies in their existing era, considering the hardware and software environment at the time, can better understand the technology itself. This article is a very superficial description of their differences, if interested can go to study their specific implementation, can find greater pleasure.
C + + 's new and malloc differences