TCS TCS -4 years ago 116
C++ Question

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!

Answer Source

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!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download