tags:

views:

165

answers:

1

Possible Duplicates:
What is the difference between new/delete and malloc/free?
In what cases do I use malloc vs new?

Why should I avoid using malloc in c++?

+4  A: 

Because malloc does not call the constructor of newly allocated objects.

Consider:

class Foo
{
public:
    Foo() { /* some non-trivial construction process */ }
    void Bar() { /* does something on Foo's instance variables */ }
};

// Creates an array big enough to hold 42 Foo instances, then calls the
// constructor on each.
Foo* foo = new Foo[42];
foo[0].Bar(); // This will work.

// Creates an array big enough to hold 42 Foo instances, but does not call
// the constructor for each instance.
Foo* foo = (Foo*)malloc(42 * sizeof(Foo));
foo[0].Bar(); // This will not work!
In silico
The comment concerning the usage of malloc is incorrect - you've allocated 42 bytes, not necessarily enough space to hold 42 instances of the type. You'd need to do `42 * sizeof(Foo)` to allocate enough space, correctly. But you're correct that the constructors would not be called.
Nathan Ernst
Yeah, I realized that after re-reading it.
In silico