0

I am not sure about something. Take linux for example; when a program exits, the kernel is responsible for cleaning after the process.

How can one be sure that physical memory is never overwritten from process A to process B (different virtual memories (page entries) leading to the same physical allocation)?

How is it prevented?

cadaniluk
  • 15,027
  • 2
  • 39
  • 67
Amy Lindsen
  • 119
  • 6
  • The OS handles the mapping from virtual memory to physical memory, in collaboration with the CPU. By simply not mapping different virtual pages to the same physical memory at the same time, physical memory is never overwritten. – MicroVirus Nov 25 '15 at 15:43

1 Answers1

1

Linux assigns pages to and frees pages from processes using the facilities described here.
(Search the kernel sources for more detailed information.)

That means, the kernel saves information about the used pages in some data structure (could be a bitmap, for example) and only the unused ones are exposed as usable to new processes.
That prevents mistakenly assigning pages in use to new process. Any behavior beyond that would be a bug and a magnificent security hole.

cadaniluk
  • 15,027
  • 2
  • 39
  • 67
  • cad, so the kernel maintains a list of free memory, alters it on mallocs or equivalent and put this memory back to the list on free or equivalent, ready to be allocated again by another process. Hence, the garbage values we can find when reading non zeroed memory? I got it straight? – Amy Lindsen Nov 25 '15 at 15:52
  • @AmyLindsen Partially. `malloc`'s implementation is, well, implementation-defined, so it **might** be implemented as an area **initially allocated** by the process. In that case, the C runtime manages the heap on its own. Concerning the garbage values - not exactly. What if someone stored a password on the heap? You'd be able to read it. Read [this](http://stackoverflow.com/questions/6004816/kernel-zeroes-memory) for more information. – cadaniluk Nov 25 '15 at 15:58
  • @AmyLindsen [That](http://stackoverflow.com/questions/3479330/how-is-malloc-implemented-internally) is also a good read. Note the "although AFAIK no malloc really gives memory segments back to the kernel with that method" in the accepted answer; that's precisely what I was talking about. – cadaniluk Nov 25 '15 at 15:59
  • @Amy: When `malloc` needs to get new memory from the OS, it will already be zeroed. If Linux (the kernel) didn't zero memory before mapping into a process that called `sbrk` or `mmap(MAP_ANONYMOUS)`, it would be leaking data from another user, or from the kernel itself, into the user process. You only get "garbage"-filled memory from `malloc()` after you've `free()`d some memory. A good implementation of `calloc()` should take advantage of this, and get zeroed pages from the OS for large allocations, and avoid writing them itself. – Peter Cordes Nov 26 '15 at 01:07