Why does _get_heap_handle equal to GetProcessHeap?

血红的双手。 提交于 2019-11-29 12:35:52

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):

  1. Switch to /MT in C/C++/Code Generation/Runtime Library (i.e. to use static c-runtime linking)
  2. Add smalheap.obj to Linker/Input/Additional Dependencies
  3. 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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!