Pergunta

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?

Foi útil?

Solução

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.

Outras dicas

If you ran foo.c in two different terminals and printed the address of a local variable, they would display the same. HOWEVER, they are two different variables which happen to have the same value.

They do not point to the same area in memory.

Forking from a shell would also get the process to have two separate and distinct variables within two different areas of virtual memory.

In fact, this is the case if you spawn a process from foo.c

If you wish to have shared memory between two process, you need to spawn threads or use shared memory.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top