1,902 views
3 votes
3 votes

MY QUESTION IS

1)WHY PRINTF() PRINT VIRTUAL ADDRESS(MENTIONED IN EXPLANTION) NOT PHYSICAL ADDRESS

2) WHY VIRTUAL ADDRESS(O/P OF PRINTF(&VAR)) OF A VARIABLE CHANGES WHEN WE RUN  A PROGRAM MANY TIMES

Consider the following code fragment:

if (fork() == 0)

{ a = a + 5; printf("%d,%d\n", a, &a); }

else { a = a –5; printf("%d, %d\n", a, &a); }

Run on IDE

Let u, v be the values printed by the parent process, and x, y be the values printed by the child process.

ANS-> u + 10 = x and v = y

Explanation: 

fork() returns 0 in child process and process ID of child process in parent process. In Child (x), a = a + 5 In Parent (u), a = a – 5; Therefore x = u + 10. The physical addresses of ‘a’ in parent and child must be different. But our program accesses virtual addresses (assuming we are running on an OS that uses virtual memory). The child process gets an exact copy of parent process and virtual address of ‘a’ doesn’t change in child process. Therefore, we get same addresses in both parent and child.

1 Answer

2 votes
2 votes
There are many secuirity concern like "Buffer overflow" attack or "stack smashing" attack, for which addresses seen in a program are always virtual. Processes on systems with virtual memory always deal with virtual addresses.This is most easily verified by making the program run in a loop and print the value with some delay, then running multiple copies of the same program. Chances are they will print the same address (unless the OS is randomizing the virtual address usage), which of course would be impossible if the addresses were physical. The memory is handled by the OS and there is a concept called "protection and secuirity" in OS which is easily overcome using virtual memory.
Virtual address does not change for a same variable. Your 2nd question is wrongly asked.The child process gets an exact copy of parent process and virtual address of ‘a’ doesn’t change in child process. Therefore, we get same addresses in both parent and child.

Related questions

0 votes
0 votes
1 answer
1
Erwin Smith asked Apr 11, 2023
781 views
void main() { int n = 1; if(fork()==0) { n = n<<1; printf(“%d, “, n); n = n <<1; } if(fork()==0) n=n+700; printf(“%d, “,n); }Which of the following output is not ...
2 votes
2 votes
3 answers
2
Philosophical_Virus asked Dec 10, 2023
876 views
Int main (){fork();printf("a");fork();printf("b");return 0;}How many distinct outputs are possible of above code? And also give outputs
0 votes
0 votes
2 answers
4
dd asked Sep 15, 2018
1,061 views
The fork system call creates new entries in the open file table for the newly created child process. [True / False][ what is open file table ? ]