New vs. malloc, QQ farm and prairie?

Source: Internet
Author: User

A few days ago I saw someone in the group talking about the difference between new and malloc, and I saw someone say that malloc is not as good as new, and it makes sense to look at the reasons why new is better than malloc, but then I thought, Suddenly I think the language of this kind of thing why must distinguish who is good who bad? any one, such as English and Chinese, an idiom in Chinese, English but a sentence to express, but sometimes the expression of English is more convenient than Chinese (of course, this is only my personal opinion). In C or C + + Also, sometimes can have a variety of expressions can achieve the same effect, such as C language, sometimes with pointers convenient, sometimes using arrays convenient, but many times, they can achieve the effect is almost. (There are many examples, such as how to access private members of a class outside of a class in C + +, which is not analyzed carefully).

         if you want to ask me new and malloc which is better, I'm sorry, It's really hard to say (in the case of not specifying which aspect), like James and Lionel Messi who is stronger (probably a bit inappropriate), such a problem in not specifying which aspect, more exactly who is which field of case can not answer. in the basketball field of course James Strong, but in the football field is naturally more powerful Messi. But the two have the same point, that is they are fast (new and malloc also have the same point, can dynamically open up memory) , new in C + + than malloc to use more extensive , but there is no new in the C language, which is naturally the situation of malloc eminence. C + + can have malloc, after all, malloc also has its own characteristics, C + + or support it, it can be understood: (two are my favorite star, here I just made an "inappropriate" metaphor, if you are both of them fans, please forgive me, Yesterday happened to be the first day of the NBA Finals, the support of the old Jayne but lost, after a few to refuel Ah, for the home to bring the title of the time to the) if let James go to play football, I believe there is a team will want him, after all, physical conditions there. Also let Messi go to the NBA as a defender, speed, but some aspects (such as height) is very disadvantage (), (unless the NBA rules, Defender shot no cap, No ridicule, he is my favorite footballer ), New and malloc are the same, and in C + + sometimes new can do it, and malloc is a little tricky.

The above is just a less appropriate metaphor, a more figurative metaphor, that is, the topic of the two differences between them like the QQ Farm (new) and the Prairie (malloc) difference. You can get a better understanding of it by looking at it:

The new operator helps you to plot the field's sub-blocks (arrays), to help you sow the kind (constructor), delete the time will help you clean up, but also provides other facilities for you to use:

And malloc gives you a lot of land, like a prairie (or a primitive prairie), what you want to do or what you need to sow on the land.

Or that sentence, the two of them each have a place to apply, more accurately in some respects than another superior place. In C + +, however, the OOP-biased language is naturally more suitable for use with new/delete.

The front said a lot of irrelevant content, the following began to cut to the point, the details of the new and malloc 10 differences:

Let's take a look at the memory angle :

1th: Where to apply for memory

The first thing to make clear is that new is an operator, and malloc is a function, and the new operator dynamically allocates memory space from the free store upper object, whereas the malloc function allocates memory dynamically from the heap. (Free storage: It is an abstract concept of C + + based on the new operator, which is a free store, as long as it is a request for memory through the new operator). However, the heap used by the malloc function is a special piece of memory maintained by the operating system, used for the dynamic allocation of the program's memory, and the C language uses malloc and free to allocate and release memory from the heap.

See here, you may have a question in mind, is that new can dynamically allocate memory on the heap, it depends on the implementation details of operator new, the specific point is to see where operator new allocates memory for the object, (There is, of course, a special case where new can not allocate memory for objects!) Positioning new can move to this point), what is positioning new? See an example:

Class Student                                      //Student Classes {public:student (); Student (string name, int age, double score), ~student ();p rivate:string name;int age;double score;}; Student::student () {Student ("", 0, 0.0);} Student::student (string name, int age, double score) {this->name = Name;this->age = Age;this->score = score;} Student::~student () {}int main () {Student stu;        return 0;}
What do you think is the value of student Stu after this statement is executed Stu? Is it 0? Unfortunately, no, there is a random value inside, why?

The reason is that when you execute student ("", 0,0.0), you do not use this constructor to initialize the current memory area, but instead initialize the memory area of a temporary object. If you want to achieve an effect, you should use placement new (locating the new expression), which should instead be in the parameterless constructor:

New (This) Student ("", 0, 0.0);
Take a look at the two forms of a positional expression:

New (place_address) type or new (place_address) type (initializer-list) place_address must be a pointer

place_address represents a memory address. The new operator calls the special operator new, which is the following version, when the new operator is called with just one address above:

void * operator new (size_t, void *)

It is important to note that this version of operator new does not allow overloading or allocating any memory, and if you look at its internal implementation, you will find that it simply returns a pointer argument with only a simple return statement, and the new expression is responsible for the Place_ addresses the specified address for initialization of the object.


2nd: Whether to specify the size of the memory

The memory allocation requested with the new operator does not need to specify the size of the memory block, the compiler calculates the type information that you enter, but malloc does not, and malloc needs to display the size of the required memory. If you have a custom class type memory allocation, we recommend that you use new.


3rd: The ability to visually reallocate memory

familiar with the C language know, if you use the malloc function to open up the memory, you can find that the original space is not enough to meet your needs, you may use the REALLOC function for memory redistribution and memory expansion. Speaking of which, we have to mention the ReAlloc function, the realloc function in the execution of the process, first of all to determine whether the current pointer to the memory of a sufficient contiguous space, if any, expand the allocated memory space in situ. If there is not enough contiguous space, it will first go to the memory to find out if there is enough memory space, if not, return null, if any, will be the new specified size allocation space, and the original data from start to finish copy to the newly allocated memory space area, and then release the original memory space area.

Unfortunately, new does not have such an intuitive facility to augment memory.


4th: Insufficient memory allocation processing

in malloc, if the memory allocation is insufficient, you can only carry a null return value with no use. There seems to be nothing else to do. But new is different, and new can throw an exception if the memory allocation is insufficient. However, the exception is thrown by operator new, of course, before throwing an exception to reflect an unmet requirement, it invokes a user-specified error handler, which is New-handler.

namespace std{     typedef void (*new_handler) ();    New_handler is a pointer type}

this pointer points to a function that has no parameters and no return value, and is also called an error-handling function. In order to specify the error handler, we need to call Set_new_handler and look at the same.
namespace std{     new_handler set_new_handler (New_handler p) throw ();}
focus on the parameters of the Set_new_handler , whose parameters are the New_handler pointer, pointing to the function that should be called when operator new cannot allocate enough memory. Of course, its return value is also a pointer to the New_handler function that Set_handler is executing (but replacing immediately) before it is called.

Then take a look at the use point :

1th: Handling of arrays during use

first of all, because malloc is in the process of implementation, it does not know what you are going to do in this open memory space, so it does not know what you want to put in this memory is an array or something else, anyway it is responsible for the size of the memory you want to open to you, And it is the return value of the address as you are done, so when using malloc to open up memory, you need to give it size, indicating the size of the array you want to open.

New[] and delete[] are specifically designed to handle array types in C + +, and if you want to open an array of 10 int, you can write it directly:

int * ptr =  new int[10];  Allocate 10 integer types
Of course, it can also be a custom type of content, such as for a student class student, you can write the following form:

Student * Pstu = new STUDENT[10]; Assign 10 a objects

here is to say if you use new[] allocated memory, then it is best to use delete[] to release, delete [] pstu, otherwise it may cause problems, In general, if there is a display definition destructor, if you need to use Delete [] to free up memory, and you use Delete to release, then generally there will be a problem. (How much you apply, then your return must be equal to the size of your application.) So use new[] in conjunction with delete[], which may cause a memory leak.                                                                                

2nd: Whether the two can call each other

If you've seen the compiler's implementation of new in C + +, you can see that the implementation of new is still called malloc at the bottom, but it does some encapsulation, which in general is called operator New/operator Delete in the implementation process. The implementation of both can be based on malloc and free. In turn, however, the implementation of malloc does not have to call new. But note that if you are using new to create a built-in type of space, then you only need to call malloc in new to open the specified size, but if it is a custom type, such as a class type, then you must be aware of the implementation of not only to open up memory space, You also need to call a certain number of constructors (specifically discussed below). Delete is the same, not only with free release, but also call the destructor, but it is important to note that the order is to call the destructor, and then free the memory space, otherwise if you first free space, equivalent to you put a space back to the operating system, but you go to use the original pointer to this space , such operations are illegal and may be lucky to succeed, but this is something to avoid.


3rd: Whether the two can be overloaded

so can the two be overloaded? Operator New/operator Delete The two can be overloaded, but the overloaded version that we define ourselves must be in the global scope or the scope of the class. You can take a look at yourself. operator new AND operator delete under the compiler, the library looks more complicated, here I simply write:

        These can throw exceptions void * operator new (size_t); void * operator new[] (size_t); void   operator delete (void *) noexcept;void   operator delete[] (void *) noexcept;//these few non-throwing exceptions void * operator new (size_t, nothrow_t &) noexcept;void * operator New[] (size_t, nothrow_t &); void   operator delete (void *, nothrow_t &) noexcept;void   operator delete[] ( void *, nothrow_t &) noexcept;
In general, we know that we have enough freedom to reload operator new AND operator delete so that we can more freely decide how we want to make space for our objects and how to reclaim objects.
However, Malloc/free does not allow overloading. In this way people should still prefer to use new and delete, compared to everyone like freedom.

4th: Whether the constructor/destructor is called during use

As mentioned above, we call constructors when we use the new operator to allocate objects, so how do we call them? Or what about the process?

first , it calls the operator new function (called the operator new[] function if it is an array) so that it can allocate a sufficiently large space, which is, of course, the original, unnamed space used to store a particular type.

The compiler then runs the appropriate constructor to construct the object and pass it an initial value.

finally , after the construction object is finished, a pointer to the object is returned.

Similarly, when you use the delete operator to free up memory space, you go through two stages:

Phase one: Call the destructor of the object.

Stage Two: The compiler will call operator delete (if an array calls operator delete[]) function to free up memory space.

To summarize, the new/delete operator invokes the constructor/destructor of the object to create or destroy the object, but malloc never invokes it.

Or take just the student class as an example:

Class Student{public:student (String name = "Jack", int age = +, double score = 98); ~student ();p rivate:string name;int Age ;d ouble score;}; Student::student (string name, int age, double score) {this->name = Name;this->age = Age;this->score = score;} Student::~student () {}int main () {Student * Pstu = (Student *) malloc (sizeof (Student));//student *pstu = new Student;return 0;}
Observing the memory content that Pstu points to will find:


After executing the statement, the contents are still random, so the student constructor is not called, so the values inside are not initialized, so it is not appropriate for malloc to open up memory space for custom types (class types).

Let's take another look at using new to assign an object:

You will find that the constructor is called, and you can see the assembly, which has a call instruction indicating that the constructor was called:



Finally, from the return value angle look at:

1th: Security of return type

when the new operator allocates space successfully, the returned type is a pointer to the type of the object, and its type matching is strict and therefore does not require the use of type conversions. But when Malloc's memory allocation succeeds, it returns void *, which is when we need to use forced type conversions to convert void * to the type we need.

As we can see from the above, new is a type-safe operator. Type safety, to a large extent, can be said to be memory security, it can be said at this point new is better to do.

2nd: The return value when memory allocation fails

to say the last point, write a little tired. When new memory allocation fails, it throws a Bac_alloc exception instead of returning null like malloc.

In the C language of memory allocation, we open to the memory of malloc is habitually empty, judge whether success! This is indispensable. But if you are a person who has just started C + +, it is possible that you will bring this habit to C + +, unfortunately this is not a good habit, because it doesn't make sense, new does not return NULL, and if the allocation fails, it throws an exception, so if you want to know if the assignment is successful , you should use an exception mechanism.

        try{                          Student *pstu = new Student;        }        catch (Bad_alloc &memexp)        {        //failed, either abort or reassign          cerr << memexp.what () << Endl;          return FALSE;        }


End with a picture:




New vs. malloc, QQ farm and prairie?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.