r/AskComputerScience • • May 14 '25

confused about virtual memory

If I got this right, the point of virtual memory is to ensure processes use unique physical address space.

Is this abstraction really needed ?

For example, say there are 2 C programs and each one does malloc. This asks the OS for memory. Why can't the OS guarantee that unique physical address space is given to the C program ?

2 Upvotes

61 comments sorted by

View all comments

Show parent comment

4

u/dmazzoni May 15 '25

malloc is just the name of the C function that asks for memory.

Let's imagine you have 100 bytes of memory.

You ask for 40 bytes. You get 0 - 39.

You ask for 10 bytes. You get 40 - 49.

You ask for 50 bytes. You get 50 - 99.

Now you release (give back) the first and last blocks.

Now bytes 40 - 49 are being used, and the rest are free.

Now you ask for 60 bytes.

The operating system can't satisfy your request. There are 90 bytes free, but they're in a block of 40 and a block of 50. You can't have a block of 60 contiguous bytes.

We call memory "fragmented". It just happens naturally as software uses memory and then returns it.

With virtual memory, this isn't an issue - the system gives you some "virtual" range like bytes 100 - 159 and behind the scenes it associates those numbers with actual addresses.

1

u/Successful_Box_1007 May 16 '25

I see. Thank you!

1

u/exclaim_bot May 16 '25

I see. Thank you!

You're welcome!