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!
VirtualAlloc manages pages in the Windows virtual memory system, while HeapAlloc allocates from a specific OS heap. Frankly, you are unlikely to ever need to use eiither of them. malloc is a Standard C (and C++) library function that allocates memory to your process.
malloc(): It is a C library function that can also be used in C++, while the “new” operator is specific for C++ only. Both malloc() and new are used to allocate the memory dynamically in heap. But “new” does call the constructor of a class whereas “malloc()” does not.
The main difference between new and malloc is that new invokes the object's constructor and the corresponding call to delete invokes the object's destructor. There are other differences: new is type-safe, malloc returns objects of type void* new throws an exception on error, malloc returns NULL and sets errno.
malloc() function creates a single block of memory of a specific size. calloc() function assigns multiple blocks of memory to a single variable.
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
!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With