in Programming edited by
412 views
1 vote
1 vote

The value of z after the execution of the following program is

void f(int x) {

staticint z;

z=z+x;

}

int main() {

int y=10;

fork();

fork();

f(y);

return 0;

}

1.30

 

2.20

 

3.40

 

4. 10

in Programming edited by
412 views

4 Comments

@UTKARSH I GOT 40 AND THIS IS EXPLANATION GIVEN

This is because z exists in separate processes, separate virtual address spaces. Changing one process won’t affect the other process.
0
0

 10 should be the correct answer. Fork is implemented using copy on write mechanism. each child will have its own address space. So updation by one process won't affect other. please read this copy on write method from galvin. :)

0
0
Ok Utkarsh I will see it in Galvin I am facing problem in this particular topic, and i wanted to ask this question that from where to refer it
1
1

1 Answer

0 votes
0 votes

                                                                

As the function $f(10)$ is called $4$ times and the variable $z$ is static.

Initially, $z=0$

On first function call, $z=0+10=10$

On second call, $z=10+10=20$

On third call, $z=20+10=30$

On fourth call, $z=30+10=40$

So, answer should be $40$

1 comment

No, The correct answer is 10.

When we call the fork() the executing program gets replicated which means every child and parent process (program under execution) has a data segment. So, the value of z=0;initially and when parent process terminates the value becomes 10 irrespective of what the child process holds in their own data segment.
0
0