I've been using pointer = new type[size]
for a while now and just recently discovered malloc
.
Is there a technical difference between malloc
and new
? If so, what are the advantages to using one over the other?
I've been using pointer = new type[size]
for a while now and just recently discovered malloc
.
Is there a technical difference between malloc
and new
? If so, what are the advantages to using one over the other?
malloc
is a function call, new in this case an expression.
The difference is; new
will allocate memory and construct all the elements of that array with the default constructor. malloc
just gives back a chunk of uninitialized memory.
Further still, ::operator new
will throw std::bad_alloc
or a new handler if one was registered.
The standard library defines a new that accepts a further parameter nothrow
which returns a 0 pointer if the allocation fails.
int *x = new(std::nothrow) int[20]; // include <new>, return 0 on failure
You can find FAQ with your question here
And another good answer: In what cases do I use malloc vs new?