1

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?

Fred Larson
  • 60,987
  • 18
  • 112
  • 174
Maxpm
  • 24,113
  • 33
  • 111
  • 170

2 Answers2

3

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
Marcus Borkenhagen
  • 6,536
  • 1
  • 30
  • 33
  • You said what I was about to, but both better and more quickly. I was just in the process of looking one thing up though: is my memory correct that in obsolete versions of the C standard, free(NULL) has undefined effect, whereas delete[] NULL has always explicitly been safe? I'm not immediately able to find any evidence for that so am starting to wonder whether it's a misconception on my part. – Tommy Dec 08 '10 at 17:31
  • Tommy, IIRC free(0) is defined. I don't know of ancient versions of C though ;) – Marcus Borkenhagen Dec 08 '10 at 17:33
  • Without having the actual specs to hand, Googling suggests that it's in C99 and probably C89, so I don't suppose it matters other than to, ummm, nullify any potential argument that delete[] is 'safer' than free... in a new/malloc discussion it might be worth pointing out the distinction between delete and delete[] though? Just as a technical difference between the two methods of memory allocation. – Tommy Dec 08 '10 at 17:40
  • Agreed, but that is way more than the scope of the original question, isn't it? – Marcus Borkenhagen Dec 08 '10 at 17:43
  • So in other words, if I use `pointer = new int[20]` I can expect the integers to all be zero, but if I decide to use `malloc` the values might be garbage? – Maxpm Dec 08 '10 at 18:27
  • Maxpm: yes. This is why, when performance is critical one uses `::operator new()` (if not even some more advanced allocator). – Marcus Borkenhagen Dec 08 '10 at 18:43
2

You can find FAQ with your question here

And another good answer: In what cases do I use malloc vs new?

Community
  • 1
  • 1
SlavaNov
  • 2,447
  • 1
  • 18
  • 26