Allocate Virtual memory before running out of RAM
is it possible, in a C/C++ program, to allocate virtual memory (Swap Spac开发者_运维技巧e) for an specific array, so that the program keeps using RAM for the rest of variables, and maybe getting some benefit at some type of problems??
For the first part: in pretty much every modern OS, there is a way to map files to a memory location. You could do so and use the file as the "swap space" you describe. The POSIX standards define mmap
(which is usable through Linux and Mac OS) and Windows has MapViewOfFile.
For the second part: it heavily depends on the type of problems you meet. Chances are it's only going to make accesses to your array slower (as in "ridiculously slower") and not help anything, unless it's an enormous array and you're looking for a way to save memory by offshoring contents to the hard drive. Normally, your OS allocates swap space itself and deals with it as it sees fit, so explicitly using a file as additional memory doesn't look like a good solution for anything to me.
You should allow the OS to handle that. If you decide to "allocate" space on the disk itself, access to your array will be very very slow and considering the array could possibly be very large operations on it would take forever. All current OS'es should support automatically placing your program memory onto swap or a page file when it sees fit. If you're not interested in a performance hit you can create your own array in "memory" but I would recommend against that as if something happens in your program during runtime then this may not get cleaned up and could lead to further problems.
精彩评论