0

Here is the code segment I am dealing with. It outputs 500, but I can not figure out, why this is happening.

#include<stdio.h>

int *f(int x){
    int p;
    p = x;
    printf("p is : %d\n",p);
    return &p;
}

int *g(int x){
    int y;
    y = x;
    printf("p is : %d\n",y);
    return &y;
}

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

    return 0;
}

What is the reason for the output of 500?

Twenty
  • 5,234
  • 4
  • 32
  • 67
Sahan Dissanayaka
  • 591
  • 2
  • 8
  • 26

2 Answers2

3

You're returning the address of a local variable.

The lifetime of the variables p and y in the functions f and g ends when those functions return. As a result, the pointers to them become invalid and attempting to dereference them results in undefined behavior.

Rather than returning pointers, just return the value directly.

dbush
  • 205,898
  • 23
  • 218
  • 273
3

Look at your function:

int *f(int x){
    int p; 
    p = x;
    printf("p is : %d\n",p);
    return &p;
}

warning: address of local variable 'p' returned [-Wreturn-local-addr]

Here variable p is created in the scope of f() after the return of function call this functions stack frame get destroyed so are everything in it, thus unexpected results. You can either return the value directly or dynamically allocate memory using malloc(), in this case variable will be stored in heap instead of f() or particular functions stack later on you can free the memory when you're done.

some user
  • 1,693
  • 2
  • 14
  • 31