Malloc function in C++

2020-02-12 07:52发布

问题:

I am transitioning to C++ from C. In C++, is there any use for the malloc function? Or can I just declare it with the "new" keyword. For example:

class Node
{
    ...
}
...
Node *node1 = malloc(sizeof(Node));        //malloc
Node *node2 = new Node;                    //new

Which one should I use?

回答1:

Use new. You shouldn't need to use malloc in a C++ program, unless it is interacting with some C code or you have some reason to manage memory in a special way.

Your example of node = malloc(sizeof(Node)) is a bad idea, because the constructor of Node (if any exists) would not be called, and a subsequent delete node; would have undefined results.

If you need a buffer of bytes, rather than an object, you'll generally want to do something like this:

char *buffer = new char[1024];

or, preferably, something like this:

std::vector<char> buffer(1024);

Note that for the second example (using std::vector<>), there is no need to delete the object; its memory will automatically be freed when it goes out of scope. You should strive to avoid both new and malloc in C++ programs, instead using objects that automatically manage their own memory.



回答2:

The direct equivalent of malloc() in C++ is operator new() which also allocates raw memory, however in most cases a new expression is what you want. A new expression both allocates an appropriate amount of raw memory and initializes an object in that memory location, returning a correctly typed pointer to the new object.

In your case , new Node is correct as it allocates memory and initializes a new Node object. Simply calling malloc and casting result to a pointer to Node won't correctly construct the Node object. This is critical if Node is not a POD-struct (e.g. when it or one of its sub-objects has a constructor that should be called).

You should avoid dynamic allocation where it is not needed; where it is needed, it is often best to initialize some sort of smart pointer with the address of the dynamically allocated object so that it's not possible to 'forget' to delete the obejct.



回答3:

One of the primary differences between new and malloc is that new will call the object's constructor.

Another difference is that new will throw an exception (may be circumvented by a compiler pragma) if the memory cannot be succesfully allocated. The malloc may cause a system signal to be generated. Although some C++ libraries implement new by calling malloc.

There may be a few instances where objects need to be dynamically allocated without invoking their constructors. In over 20 years, I haven't come across any (not even in the embedded systems arena).



回答4:

Well, the one thing I can think of, if you're using new you're going to miss realloc if you end up needing it.



回答5:

They key situation in which you must use malloc is if the original code ever calls realloc. Of course you can reimplement everything needed, but there isn't that much advantage in doing so.



回答6:

My habit is to use malloc() for primitive types and C compatible structs, and new for everything else.



回答7:

In general, use new except when interfacing with C code.

The key point on this is that what is allocated with new must be freed with delete, and what is allocated with malloc must be freed with free. You cannot allocate with new and free with free() or vice-versa. So, about the only time you need malloc is when you need to pass data off to some C code that might free() or realloc() it.