views:

109

answers:

2

is it possible, in a C/C++ program, to allocate virtual memory (Swap Space) 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??

+7  A: 

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.

zneak
+1 -- though the call you're looking for on Windows is `MapViewOfFile`.
Billy ONeal
@Billy O'Neal thanks, changed that.
zneak
thanks, then the automatic OS swap should take care hopefuly of what someone needs, i was just curious if there was a better workaround
Cristobal
A: 

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.

Jesus Ramos
ok, very clear, i think ill just use swap handled by OS. if it handles it intelligently, then i wouldnt achieve a better solution than that
Cristobal
and of course, thanks!
Cristobal
if it is a lot of memory at once you may run into hard fault issues that cause your program to run slow because most of its memory is in the page/swap, just try and keep it as clean as possible to avoid this causing large performance problems depending on what you want to do
Jesus Ramos