malloc vs api heapalloc

Started by
3 comments, last by BrianLarsen 13 years, 12 months ago
so what exactly is the difference between malloc and heapalloc api function? why would u want to use one over the other?
Advertisement
HeapAlloc is a Windows API function, whereas malloc is a C library function. On Windows, malloc calls HeapAlloc internally, however malloc is standard C so it's completely portable and will be implemented appropriately on any target platform.

You'd really only use HeapAlloc directly (or any of the other flavors of allocation on Windows) if you had specific need for their additional functionality, i.e. creating and allocating from multiple heaps.
I thought malloc was suppose to be an efficient allocation mechanism on top of HeapAlloc, but looking at the crt source code you can see that malloc (and operator new) pretty much just calls HeapAlloc directly, so from a logic standpoint they are effectively the same. (Maybe HeapAlloc already is an optimized memory allocator?)
Quote:malloc pretty much just calls HeapAlloc directly

That's true on x64, but there used to be a small-block heap (and an older still implementation) on top of HeapAlloc.

Quote:why would u want to use one over the other?

HeapAlloc can be told not to take a lock, so that might be useful for avoiding serializing multiple threads. (While that's better than malloc, I'd prefer TCMallor or per-thread pools for such use cases.)
E8 17 00 42 CE DC D2 DC E4 EA C4 40 CA DA C2 D8 CC 40 CA D0 E8 40E0 CA CA 96 5B B0 16 50 D7 D4 02 B2 02 86 E2 CD 21 58 48 79 F2 C3
Its usually better to use calloc which is a somewhat safer replacement for malloc.

Calloc/Malloc are both standard C library routines and portable....

This topic is closed to new replies.

Advertisement