开发者

C++ Reserve Memory Space

is there any wa开发者_如何学运维y to reserve memory space to be used later by default Windows Memory Manager so that my application won't run out of memory if my program don't use space more than I have reserved at start of my program?


There is no point in doing this kind of thing when you have virtual memory.


Though it's usually a really bad idea (as others have already pointed out), yes Windows does allow it. Look up VirtualLock if you really insist. At least 99% of the time, this is the wrong thing to do, but it's always possible (though extremely unlikely) that what you're doing falls into the fraction of a percent of things that justify it.


At any given moment, your application doesn't necessarily have any physical memory.

If your app is waiting on an IO operation for a while and the user starts editing a video, your app may disappear from physical memory altogether. It only exists in the page file. When the IO operation completes and one of your threads needs to start running again, you get some physical memory back.

All you really get to allocate is parts of your process's address space. Parts of it may be mapped to files (such as your EXE or any native DLLs that didn't need to be rebased). Other parts may be "memory allocation", but really that just means they are mapped to places in the page file.

None of it is "really" memory in any reliable sense.

The thing you can certainly run out of is room in your address space. If you allocate 100MB chunks a few times, plus a few smaller ones, it won't be long before you've fragmented the address space (which by default only gives you enough room for about 20 such chunks, and any given chunk has to fit into one contiguous region).


Not implicitly. There is no way to tell the C memory manager (the one which gives you memory when you call malloc or new) to reserve space.

What you can do is use your own specialized allocator or buffer pool and manage the allocations and memory reservation manually.


Edit -
On windows you can use VirtualAllocEx and VirtualFreeEx to ask windows to reserve memory pages for you. But there is no way to tell malloc and new to use this memory. If you choose to go this path you'll need to implement your own memory manager.


This isn't even remotely portable but in many systems memory you allocate is not returned to the operating system when you free it, it's just put back on the free list for that program.

So if you allocate a block big enough when your program starts up and then free it immediately then that memory will be available from then onwards for the memory allocator to hand out within that program.

You'd certainly have to make sure that your platform worked in that way though. At best it's unportable though, but at worst it shouldn't hurt anything.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜