And I quote from MSDN http://msdn.microsoft.com/en-us/library/aa366533(VS.85).aspx:
The malloc function has the disadvantage of being run-time dependent. The new operator has the disadvantage of being compiler dependent and language dependent.
Now the questions folks:
a) What do we mean that malloc is run-time dependent? What kind of dynamic memory allocation functions can be independent of run-time? This statement sounds real strange.
b) new is language dependent? Of course it should be right? Are HeapAlloc, LocalAlloc etc language independent?
c) From a pure performance perspective are the MSVC provided routines preferable?
Arpan
The problems with malloc and new arise when you use DLLs. Depending on build options, a DLL may have its own copy of the CRT. That makes it use its own heap to allocate memory from, a different heap than the one used by the EXE. This causes failure when memory is allocated by one module and released by another. Very common when you use STL.
One way to solve it is by compiling code with the /MD option. That forces use of a shared copy of the CRT, stored in its own DLL. Problem solved, there's now only one allocator, using a single heap.
This issue also arises with COM, it allows different languages to interop. They would of course never share an allocator since those language have different runtime support libraries. By contract, COM code must use a single allocator provided by the COM runtime support, CoTaskMemAlloc().
Note that HeapAlloc() cannot solve this problem. It requires a handle to a heap, returned by HeapCreate(). Different modules would have to share that handle to avoid trouble.
Update: addressed in VS2012, the CRT now allocates from a shared heap, the default process heap (GetProcessHeap function).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With