5

For example, I heard in class that global variables are just put in a specific location in memory. What is to prevent two programs from accidentally using the same memory location for different variables?

Also, do both programs use the same stack for their arguments and local variables? If so, what's to prevent the variables from interleaving with each other and messing up the indexing?

Just curious.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
i love stackoverflow
  • 1,555
  • 3
  • 12
  • 24

3 Answers3

6

Most modern processors have a memory management unit (MMU) that provide the OS the ability to create protected separate memory sections for each process including a separate stack for each process. With the help of the MMU the processor can restrict each process to modifying / accessing only memory that has been allocated to it. This prevents one process from writing into a another processes memory space.

Most modern operating systems will use the features of the MMU to provide protection for each process.

Here are some useful links:
Memory Management Unit
Virtual Memory

Chimera
  • 5,884
  • 7
  • 49
  • 81
5

This is something that modern operating systems do by loading each process in a separate virtual address space. Multiple processes may reference the same virtual address, but the operating system, helped by modern hardware, will map each one to a separate physical address, and make sure that one process cannot access physical memory allocated to another process1.


1 Debuggers are a notable exception: operating system often provide special mechanisms for debuggers to attach to other processes and examine their memory space.
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
  • The fact that some OSs require a certain degree of elevation to debug some or all programs reveals this - if the OS is insisting on anything, then clearly the OS is having a say. Another exception is shared memory, where programs use some memory mapped to both their virtual memory space to communicate, though the very concept reveals that being in the same memory-space isn't the norm. – Jon Hanna Aug 31 '12 at 19:11
3

The short answer to your question is that the operating system deals with these issues. They are very serious issues, and a significant percentage of an operating systems job is keeping everything in a separate space. The operating system runs programs that track all the other programs and make sure they are each using a space. This keeps the stacks separate too. Each program is running its own stack assigned by the OS. How the OS does this assigning is actually a complex task.

usumoio
  • 3,500
  • 6
  • 31
  • 57