malloc() vs. HeapAlloc()
What is the difference between malloc() and HeapAlloc()? As far as I understand malloc allocates memory from the heap, just as HeapAlloc, right?
So what is the difference?
Thanks!
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
!
With Visual C++, the function malloc()
or the operator new
eventually calls HeapAlloc()
. If you debug the code, you will find the the function _heap_alloc_base()
(in the file malloc.c
) is calling return HeapAlloc(_crtheap, 0, size)
where _crtheap
is a global heap created with HeapCreate()
.
The function HeapAlloc()
does a good job to minimize the memory overhead, with a minimum of 8 bytes overhead per allocation. The largest I have seen is 15 bytes per allocation, for allocations ranging from 1 byte to 100,000 bytes. Larger blocks have larger overhead, however as a percent of the total allocated it remains less than 2.5% of the payload.
I cannot comment on performance because I have not benchmarked the HeapAlloc()
with a custom made routine, however as far as the memory overhead of using HeapAlloc()
, the overhead is amazingly low.
malloc
is a function in the C standard library (and also in the C++ standard library).
HeapAlloc
is a Windows API function.
The latter lets you specify the heap to allocate from, which I imagine can be useful for avoiding serialization of allocation requests in different threads (note the HEAP_NO_SERIALIZE
flag).