Hello everyone,
On Windows, when we allocate large amount of memory, new will call VirtualAlloc directly, other than call HeapAlloc then through HeapAlloc call VirtualAlloc indirectly?
Anyone to clarify this?
thanks in advance,
George
Printable View
Hello everyone,
On Windows, when we allocate large amount of memory, new will call VirtualAlloc directly, other than call HeapAlloc then through HeapAlloc call VirtualAlloc indirectly?
Anyone to clarify this?
thanks in advance,
George
Implementation specific, once again.
All libraries are not restricted to doing that since all the standard says AFAIK is that new allocates memory for C++.
For Microsoft's implementation, new always calls HeapAlloc.
What difference does it make? The only thing that really matters is the whether the allocation succeeded or not, and that if it succeeds, that the returned memory address is available to the application.
If you really want to know how it works, use WinDBG and put breakpoints on each of those entry points in a particular application. I expect VirtualAlloc is never called by new - it is pretty much meaningless to do so - it may of course happen during HeapAlloc, but in that case, it's probably the kernel-internal form of VirtualAlloc, rather than VirtualAlloc as a external function.
--
Mats
Thanks Mats,
I just want to learn how Windows optimize memory allocation according to the request size of memory to be allocated by asking this question -- the actual purpose is more about to get the idea other than get the real internal function to be called. I just want to learn this idea and improve my own engineering work.
regards,
George
For 99.9% of all memory allocations, HeapAlloc is fine. If you are working with special memory (such as in device drivers or applications that talk directly to lower level device drivers), you may find that VirtualAlloc is meaningfull - I may have stated earlier that VirtualAlloc isn't for small allocations, but it's not really a suitable replacement for HeapAlloc for large allocations either. Pretty much the answer is "If you don't know for sure that you need VirtualAlloc, you probably don't".
--
Mats
The only advantage of VirtualAlloc that I know of is that you can reserve and commit specific virtual memory areas, making it perfect for expanding arrays.
But that is usually not a very good advantage, since it would rarely be used I think.
All of the usages of VirtualAlloc are rare - that was my point. Expanding arrays is fine, but you do need to know the maximum size of the array, and once you have reserved the memory, you can't use it for anything else.
Setting access privileges is even rarer - I have seen code that does that, but it's not exactly mainstream code.
--
Mats