3

Possible Duplicate:
What's the differences between VirtualAlloc and HeapAlloc?

I would like to pre-allocate a large chunk of memory, say 1gb to implement a memory pool. Virtual Alloc allocates using page size of 4kb. What is the advantage of using virtualalloc over new in this scenario? Should new not be used for this scenario or is there any disadvantage of using new over virtual alloc?

Community
  • 1
  • 1
Sriram Subramanian
  • 2,623
  • 5
  • 32
  • 35
  • 1
    duplicate http://stackoverflow.com/q/872072/79455 – rve Apr 15 '12 at 08:34
  • If you allocate large chunks of memory, and aligning it on page boundaries is an advantage, I bet `new` will do that as well. One difference is that `new` is part of the language and `VirtualAlloc` is part of a specific operating system. – Bo Persson Apr 15 '12 at 09:55

1 Answers1

5

With VirtualAlloc you can reserve 1gb address range. Later you can commit parts of it on demand - so that to given chunks of reserved addresses are assigned actual physical memory blocks. Reservation should never fail, while commit might fail if physical memory is short. Actually with paging file on windows this should also always succeed.

new will reserve and commit 1gb block.

So if you need to have instant access to whole 1GB blocke, then go ahead and use new.

If you dont need access to whole 1GB block at the very begining, and you can write your algorithm so that it will commit parts of memory on demand then VirtualAlloc can optimize your memory comsumption.

If you will consider using VirtualAlloc for your purposes, then you might find it hard to decide when and how to commit memory. One nice method I found in Jeffrey Richter's book (Advanced Windows 3rd ed.) is to use Structured Exception Handling. Once your code touches uncommited memory exception is thrown, all you have to do is to catch it, commit the memory and then tell the system to retry the instruction where problem occurred. I never tried this, but from my knowledge this is how stack actually works.

marcinj
  • 48,511
  • 9
  • 79
  • 100