tags:

views:

289

answers:

6

Possible Duplicate:
In what cases do I use malloc vs new?

Duplicate of: http://stackoverflow.com/questions/184537/in-what-cases-do-i-use-malloc-vs-new/ and http://stackoverflow.com/questions/808148/when-to-use-malloc-instead-of-new

Does anyone have real life programming scenarios where using "malloc" instead of "new" in C++ was justified?

A: 

The most obvious scenario would be integration with a legacy system the requires you to pass or accept ownership of some memory as you shouldn't mix new/free or malloc/delete.

I have never used malloc from C++

jk
+2  A: 

To new is C++;
To malloc is C;
To mix them is sin.

There is no very good reason to do so and this question is very much related to this one.

TheMachineCharmer
Nice, but doesn’t really address the question.
Konrad Rudolph
not only that but that little rhyme imples there is a good reason namely when you need to mix C and C++ e.g. interface to a legacy system
jk
A: 

The only example of a somewhat justified use of malloc in C++ is in the creation of a hand-rolled memory allocation scheme where a large chunk of raw memory is allocated, and then small objects are created within this buffer using placement-new.

However even this use is questionable, as the same goal can and probably should be achieved by using either new or operating-system-provided allocation functions to create an initial large buffer of char, then placement-newing objects within that.

John Dibling
A: 

Here are some compares: http://www.velocityreviews.com/forums/t288250-malloc-vs-new.html

Ervin
+3  A: 

new always invokes a constructor (although in the case of PODs something else happens). Sometimes – very rarely – you want to deal with raw memory, not associated with any type. This can be the case when you’re implementing your own allocator class. Even then, malloc is rarely the right thing to do but sometimes you may want to take advantage of realloc i.e. be able to resize the underlying storage more efficiently. This is one scenario that would require malloc to get the initial storage.

Another actual use-case for raw memory is when you find yourself implementing a “non-predictable” pseudo-random number generator (don’t!). In order to increase the entropy available to the generator, you might use uninitialized memory as a basis for the random seed. Entropy from various sources in the hardware is crucial for such operations so using uninitialized memory (about which not many predictions can be made) can be desirable, if you know exactly what you’re doing.


For completeness’ sake I should point out that the same can be achieved by calling ::operator new instead of malloc. The latter also does some checking to see whether the required amount of memory could be allocated successfully and invokes the appropriate callback handlers if something goes wrong (cf. _set_new_handler). Last but not least, ::operator new will throw std::bad_alloc if no handler manages to free enough memory (unless std::nothrow was specified as the second argument, in which case 0 will be returned).

Konrad Rudolph
+1 This is one good reason. :)
TheMachineCharmer
I'm not convinced that uninitialised memory is a worthwhile source of entropy. I guess there's no harm in throwing it into the pool, if you happen to know that reading uninitialized values is safe in your implementation, on grounds that "every little helps". But you would have to estimate its entropy as 0, because it might be always all 0, or it might be maliciously manipulated to contain values of the attacker's choice, or some such. In any case, even `new char[n]` would do the same job of giving you uninitialised memory so it's still not a case for `malloc`. I think `realloc` is it, really.
Steve Jessop
Oh, and "because the interface I'm using says I must provide a block that can be freed with `free`", of course.
Steve Jessop
Konrad Rudolph
That was different. The issue there was that a function to *write* random data into a buffer (RAND_bytes) was first *reading* the buffer into the entropy pool with an estimate of 0. This provoked valgrind warnings (reading uninitialized data), which a Debian developer "fixed" in the wrong place, with the result that calls to RAND_add didn't read anything to the pool either. At no point did the randomness depend on uninitialized data, but it did rely on actually calling MD_update from time to time. See http://research.swtch.com/2008/05/lessons-from-debianopenssl-fiasco.html
Steve Jessop
To be specific, the fix wasn't to "initialize the memory" as you say, the fix was to remove the call that read the uninitialized memory, on grounds that "adding entropy from uninitialized memory isn't essential". As it turned out, this same call was in other cases reading *initialized* memory that contained almost all the entropy that ever went into the pool. The result was an entropy pool which actually contained in the best case about 15 bits of entropy, but which was estimated as "yeah, loads of entropy for everyone!".
Steve Jessop
@Steve: thanks for putting me right. I had actually wondered that the only other source of randomness would be the process ID but I didn’t pursue the matter.
Konrad Rudolph
As for how the confusion arose in the first place, there was actually *another* patch submitted for the same problem (i.e. Valgrind complaining about uninitialized memory) that used `memset` to initialize that particular memory region.
Konrad Rudolph
A: 

Realloc may only be used on memory locations that are malloced. Realloc prefereably resizes a memory block instead of allocating a new one. Memory allocation is relatively expensive in C/C++ so this could be an advantage in performance.

GeirGrusom