According to this article, CRT uses separate heap (is it private heap?), but this little example shows that CRT heap and Default heap are the same:
HANDLE heaps[64];
DWORD heapCount = GetProcessHeaps(64, heaps);
for (int i = 0; i<heapCount; i++)
printf("heap %d : [0x%x]\n", i, heaps[i]);
printf("crt heap[0x%x], default heap[0x%x]\n", _get_heap_handle(), GetProcessHeap());
In what cases GetProcessHeap and _get_heap_handle return different handles?
// Compiled with VS2012 (Platform toolset v110)
This is new for VS2012, the CRT now uses the default process heap to allocate from. Previous versions have always created their own heap.
A significant advantage of using the default heap is that interop with code in a DLL will be a lot easier, it can significantly reduce the trouble of having to use a DLL that has its own copy of the CRT linked-in. Assuming that copy is also 2012+ vintage of course.
A potential disadvantage is that it is more difficult to generate a meaningful diagnostic or cleanly shutdown when the process heap becomes corrupted, Windows also uses that heap. And memory corruption in your code can destabilize OS calls, the kind that doesn't involve kernel calls, anything is possible there. I can imagine a security risk as well, I assume that this choice was made once they felt comfortable with the secure CRT enhancements.
The C Runtime source (malloc.c) shows that all the CRT allocations are created from _crtheap
(which is what _get_heap_handle
returns). In heapinit.c, _crtheap
is set to GetProcessHeap
. There's a separate allocation routine in smalheap.c that sets _crtheap
to HeapCreate
.
However, it's not clear to me (there's no project file, unfortunately) which CRT versions use smalheap.c and which CRT versions use heapinit.c.
FWIW, in addition to Hans's answer. I've managed to force VS2012 CRT to use private heap with below options (unfortunately with linker warnings):
- Switch to /MT in C/C++/Code Generation/Runtime Library (i.e. to use static c-runtime linking)
- Add
smalheap.obj
to Linker/Input/Additional Dependencies - Add
/FORCE:MULTIPLE
to Linker/Command Line/Additional Options (to avoid LNK2005 error for _heap_init and friends)
IMHO, it's sad that we do not have an option for private heap and c-runtime dynamic dll. This would help with memory leaks in 3rd party libraries. In case of long running process you can just unload everything and load again.
From the Article, CRT creates its own private heap, which resides on top of the Windows heap.
CRT allocates/de-allocates from the same default process heap. By private it means all the house keeping of objects is private to CRT.
来源:https://stackoverflow.com/questions/18955871/why-does-get-heap-handle-equal-to-getprocessheap