Search code examples
memorymappingvirtual-address-space

What are the cases when a program has the same virtual address space


If you ran a program foo.c in two different terminals, and printed the address of the local variable being executed. They would be same. However, in context of forking and executing say for example inside shell, I run a program such foo.c . It will create an exact same copy of the shell and then execute foo.c . Will they have the same virtual address space. And what if a program recursive calls itself, will the same variable recursively called still have the same address space and how does this program grow inside its own address space?


Solution

  • If you ran a program foo.c in two different terminals, and printed the address of the local variable being executed. They would be same.

    Not necessarily, modern operating systems use address space layout randomization, meaning memory addresses can (and do) change from one execution to the next.

    in context of forking and executing say for example inside shell, I run a program such foo.c . It will create an exact same copy of the shell and then execute foo.c . Will they have the same virtual address space.

    No, each process has its own virtual address space. The addresses of variables might look the same, but writing to a local variable in one process has no impact on the other process (unless you've explicitly shared memory)

    And what if a program recursive calls itself, will the same variable recursively called still have the same address space and how does this program grow inside its own address space?

    Research the difference between processes and threads to get a better understanding of what is going on here. If a program forks, the child process has a separate adress space. If a function calls itself within a program, it will execute in the same address space but local variables will be separate in each stack frame. Global (or static) variables will be at the same memory address across function calls.