Why don't windows targets use malloc instead of HeapAlloc?

The std targeting Windows allocates with Heap* functions:

But as we know, all versions of msvcrt and ucrt provides malloc functions. Why don't we use exsisting CRT functions instead of using raw Windows APIs?

I don't know anything about this, but what would be the advantage?

I believe some reasons to use HeapAlloc directly are:

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

  • The CRT uses its own heap (_crtheap) rather than GetProcessHeap, which could increase fragmentation when mixing both types of allocation (and as retep998 noted in the RFC 1183 discussion, the process heap is already used by system code outside our control, so we can't create programs that use only _crtheap).

  • When using HeapAlloc and GetProcessHeap, you can create a pointer in one DLL and free it in another. If you use the CRT allocator, this can lead to undefined behavior.

(Note: In some versions/configurations of the CRT, malloc does use the process heap rather than creating its own heap. However, I don't think we can rely on that in general.)


This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.