malloc() vs. HeapAlloc()
Actually, malloc() (and other C runtime heap functions) are module dependant, which means that if you call malloc() in code from one module (i.e. a DLL), then you should call free() within code of the same module or you could suffer some pretty bad heap corruption (and this has been well documented). Using HeapAlloc() with GetProcessHeap() instead of malloc(), including overloading new and delete 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.
You are right that they both allocate memory from a heap. But there are differences:
malloc()
is portable, part of the standard.HeapAlloc()
is not portable, it's a Windows API function.
It's quite possible that, on Windows, malloc
would be implemented on top of HeapAlloc
. I would expect malloc
to be faster than HeapAlloc
.
HeapAlloc
has more flexibility than malloc
. In particular it allows you to specify which heap you wish to allocate from. This caters for multiple heaps per process.
For almost all coding scenarios you would use malloc
rather than HeapAlloc
. Although since you tagged your question C++, I would expect you to be using new
!