0

I cannot understand what happens here clearly.

#include  <stdio.h>
#include  <stdlib.h>
#include  <unistd.h>

int *f(int x){
    int p;
    p=x;
    return &p;
}

int *g(int x){
    int y;
    y=x;
    return &y;
}


int main(){
  int *x,*y;
  x=f(1000);
  y=g(250);
  *x = *x + 250;
    printf("%d\n",*y);
    return 0;

}

output:- 500

How come line "*x = *x + 250" change "*y" value? why the output is not 250?

piumi
  • 1
  • 5

1 Answers1

1
int *f(int x){
    int p;
    p=x;
    return &p;
}

In this function (and in g), you are returning the address of a local variable. When the caller uses this address, it is invalid, because it is referring to a variable which is destroyed (its like using a pointer to freed dynamic memory). This results in undefined behavior.

lost_in_the_source
  • 10,998
  • 9
  • 46
  • 75
  • yeah I got that error but unfortunately this is a code from one of our exam papers in Operating systems. there they ask for the output. Is there anyway to guess the output 500? – piumi Nov 07 '17 at 12:50
  • 1
    @piumi maybe the answer is just: _the behaviour of this program is undefined because we use the pointer to a local variable that has gone out of scope and therefore the output cannot be predicted_. Check [this](https://www.ideone.com/6Z3ust). IMO this is a trick question. – Jabberwocky Nov 07 '17 at 12:59
  • @piumi if the memory address of the `p` variable in `f` is not overwritten once the `f` function has returned and if the `y` variable in `g` is allocated in the same momory location than `p` was allocated in the `f` function and if the memory address of the `y` variable in `g` has not been overwritten once the `g` function has returned, well then the result may be 500. That's a lot of ifs. – Jabberwocky Nov 07 '17 at 13:18
  • @Michael Thanks a lot for your explanation. :) – piumi Nov 07 '17 at 16:26