tags:

views:

320

answers:

7

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?

+16  A: 

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

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

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.

Kristopher Johnson
You might also use `malloc` if you are doing custom memory allocation via your own `operator::new`.
Troubadour
And remember that new throws a std::bad_alloc exception on failure unless call with the nothrow modifier!
gbrandt
Should perhaps add that new is type safe, while the return from malloc is void*.
Joel
+7  A: 

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.

Charles Bailey
+2  A: 

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.

nc3b
`realloc` doesn't work with non-POD types so using a `vector` is almost always preferred in C++.
Charles Bailey
+1  A: 

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.

Heath Hunnicutt
`realloc()` is frequently bad news in C++, as non-POD data objects are usually allergic to being moved around arbitrarily. Use a `vector<>` instead. It not only does the memory management for you, it does it correctly.
David Thornley
A: 

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

Joshua
+3  A: 

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).

Thomas Matthews
+2  A: 

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.

Michael E