I have searched for this on various links, but still the doubt persist.
I do not understand the difference between LocalAlloc
vs GlobalAlloc
vs malloc
vs new
for memory allocation.
I have gone through this link of MSDN:
Comparing Memory Allocation Methods
Please explain the following statement:
The malloc function has the disadvantage of being run-time dependent. The new operator has the disadvantage of being compiler dependent and language dependent
Excerpts from Raymond Chen's OldNewThing
Also, the link specified by you clearly says that,
For your confusion on malloc vs new, Billy ONeal's answer summarizes that pretty clearly.
For the difference between malloc and HeapAlloc, David Heffernan's and Luis Miguel Huapaya's answer combined gives the perfect solution::
malloc
is portable, part of the standard.malloc
(and other C runtime heap functions) are module dependant, which means that if you callmalloc
in code from one module (i.e. a DLL), then you should callfree
within code of the same module or you could suffer some pretty bad heap corruption.HeapAlloc
is not portable, it's a Windows API function. UsingHeapAlloc
withGetProcessHeap
instead ofmalloc
, including overloadingnew
anddelete
operators to make use of such, allow you to pass dynamically allocated objects between modules and not have to worry about memory corruption if memory is allocated in code of one module and freed in code of another module once the pointer to a block of memory has been passed across to an external module.GlobalAlloc
andLocalAlloc
are old functions from the 16 bit era. The difference was that you sometimes had to be able to allocate memory only used in your segment (that used near pointers), and sometimes needed to allocate memory to be shared with other processes and segments on the system. Today, these guys forward in some form or another to the HeapXxx functions, such asHeapAlloc
. If you're writing new code and need to avoid linking with the C runtime, you should use the HeapXxx functions instead. Of course, if you call any of these, your program will only compile and run on Windows.malloc
is "run-time dependent" in that using it requires that you link against the C run-time (CRT). The CRT is the library that contains all the other standard C library functions, likeprintf
orqsort
. You can write a plain Win32 API program without linking with this (but I honestly can't see why you'd want to do that in real software).new
is compiler dependent and language dependent in that they require a compiler that can compile C++. (And usuallynew
is implemented in terms ofmalloc
, so it'll probably require using the CRT as well)