Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a fundamental difference between malloc and HeapAlloc (aside from the portability)? [duplicate]

I'm having code that, for various reasons, I'm trying to port from the C runtime to one that uses the Windows Heap API. I've encountered a problem: If I redirect the malloc/calloc/realloc/free calls to HeapAlloc/HeapReAlloc/HeapFree (with GetProcessHeap for the handle), the memory seems to be allocated correctly (no bad pointer returned, and no exceptions thrown), but the library I'm porting says "failed to allocate memory" for some reason.

I've tried this both with the Microsoft CRT (which uses the Heap API underneath) and with another company's run-time library (which uses the Global Memory API underneath); the malloc for both of those works well with the library, but for some reason, using the Heap API directly doesn't work.

I've checked that the allocations aren't too big (>= 0x7FFF8 bytes), and they're not.

The only problem I can think of is memory alignment; is that the case? Or other than that, is there a fundamental difference between the Heap API and the CRT memory API that I'm not aware of?

If so, what is it? And if not, then why does the static Microsoft CRT (included with Visual Studio) take some extra steps in malloc/calloc before calling HeapAlloc? I'm suspecting there's a difference but I can't think of what it might be.

Thank you!

like image 836
user541686 Avatar asked Jan 03 '11 21:01

user541686


People also ask

Does malloc use HeapAlloc?

malloc on Windows calls HeapAlloc , so it involves an extra layer of function calls and argument translation compared to calling HeapAlloc directly.

Does malloc take in bytes or bits?

The malloc() function takes a single parameter, which is the size of the requested memory area in bytes. It returns a pointer to the allocated memory. If the allocation fails, it returns NULL.

Is VirtualAlloc in the heap?

VirtualAlloc manages pages in the Windows virtual memory system, while HeapAlloc allocates from a specific OS heap.


1 Answers

As I found out the hard way...

The difference isn't fundamental, but HeapReAlloc (which uses RtlReAllocateHeap) does not automatically treat a null pointer as a hint to call HeapAlloc; it fails instead.

like image 116
user541686 Avatar answered Jan 02 '23 11:01

user541686