In the C world, you would use the malloc() and free() library calls to allocate and deallocate memory chunks for your program, in that order. On the other hand, in C++ you can use the new and delete operators for the same purpose.

However, the two pairs used for the mechanics of memory management in C and C++ as enumerated above differ fundamentally in how they work.

For one thing, while malloc/free are standard library functions, the new/delete pair are part of the C++ language specification itself, that is, they are first class citizens (operators) within the language. This should be considered significant to the kind of importance that C++ places on both, memory management where the rubber meets the road, and on a higher, more abstract level, the creation and deletion of objects, the lifeblood of any C++ program. (Remember, C++ is object-oriented.)

That, of course, is only one aspect of the entire set of benefits that C++ affords to programmers. The malloc/free pair is “unintelligent” in that the two functions only allocate/deallocate memory, and that’s it; The new/delete operator pair, on the other hand, go far beyond that: they also invoke the constructor and destructor upon the object getting created. Ergo, it can be said that the new/delete operator pair are more “aware” of the class being instantiated, and therefore handle memory management more effectively.

This has some positive fallouts: While malloc() returns a void*, new returns a pointer to the actual type being created. Owing to this same “class awareness,” the new operator does not need any argument specifying the number of bytes required, as against the malloc() function which is parameterized, that is, it does require a size_t type. The new operator figures out the required number of bytes.

The new operator also has a better way to allocate arrays, unlike the malloc() library function which just allocates a chunk and it is left to the programmer to “slice” the chunk into the required number of elements.

Memory allocation failure is also handled more gracefully: While malloc() returns a NULL, the new operator will throw an exception.

Other than these benefits, the behavior of the new operator itself can be modified in terms of how it works (via operator overloading), or how the allocation works (via set_new_handler).

Original post: https://www.quora.com/How-is-dynamic-memory-allocation-in-C++-better-than-dynamic-memory-allocation-in-C/answer/Najeeb-Shaikh

Please spread the word among your friends & associates