Unfortunately, all the answers so far have been incomplete.
In order for a program to use memory, it has to refer to them by an *address*, which is just a number that points to one particular part of memory. So a program might read from address 1234, add 10 to it, and write the result to address 3456.
The problem with that is two-fold:
– Some addresses are special. For example, it might be used to communicate with a peripheral, like a USB port. So inadvertently writing to that special address might end up sending it to your mouse, which might cause it to do weird things.
– If you want to run more than one program at a time, they would have to share memory. They can cooperate and not trample over each other’s assigned memory, but it’s still a bad idea for privacy if a random game you downloaded can potentially read the data in your banking app.
So, virtual memory is a set of memory addresses (i.e., an “address space”) that’s set up by the operating system for you. To protect everybody, the virtual memory presented to one app would not map it to the special peripheral communication addresses, and would not map it to RAM that other apps are using. So the game’s address 1234 might be referring to an entirely different physical location than the banking app’s address 1234, because both their address spaces are now virtual. It’s much more convenient to write each app now because you don’t have to worry about trampling over somebody else.
From here, you can then implement the memory swapping trick that others are talking about. The OS can give each app a lot of address space but not actually map any of it to real RAM. When your app tries to use any of that space, the OS will actually be alerted, at which point it can do a lot of magical things, such as:
– Find some free physical RAM, or failing that:
– Throw out some other app’s code* that was taking up space, or failing that:
– (Optionally) compress some other app’s data and write it to disk, thus freeing up RAM.
Once the OS figures out what RAM to actually give you, it wipes the RAM for privacy reasons, maps into your address space, and returns control to your app. The memory operation is then allowed to proceed as if the RAM had been there all along.
TL;DR: virtual memory is primarily required to protect the system from apps that make mistakes or are malicious, but can also be used to let multiple apps each think that they have more memory than they really do, which is convenient for programmers.
* This is fine because the code is already on disk somewhere, so we can load it back if later needed
Latest Answers