Exactly how virtual memory is implemented is complex, but as an over-simplification:
- You run programs that need memory. The operating system takes care of tracking which program is using what portions of memory, and allocating each program the amount of memory it needs.
- Those programs will need more memory as they do their jobs. Opening a large document may cause your word processor to request additional memory from the operating system in order to hold the document.
- If there isn’t enough RAM available to satisfy a request, the operating system may decide that another program’s needs are less “important.” Some of that program’s memory will be freed, first by writing the contents to disk (the memory is “swapped out”), and then allocated to the program making the request.
- Later, when the program whose memory was swapped out needs it back, that memory can be “swapped in” by reading it back from disk. This might cause memory from another program to be swapped out to disk to make room.
Remember that the operating system itself is just a program; needs memory too. It can allocate memory to itself, and its memory may get swapped out to disk as other needs arise.
(This is an excerpt from the lengthier Ask Leo! article: What is Virtual Memory?)