0

I've tried writing this code and the two printf statements appear to give segmentation fault. why isn't the output 5? what went wrong? and how to edit this code in a way such that it prints 5?

#include <stdio.h>

int* fun(int x){
    x=5;
    return &x;
}

int main() {
    int x = 3;
    int* p = fun(x);
    printf("%d",*(fun(x)));
    printf("%d",*p);

    return 0;
}
ChrisMM
  • 8,448
  • 13
  • 29
  • 48
momat
  • 9
  • 1
  • 5
    Your `fun` is returning a dangling pointer, since the variable it referred to no longer exists – UnholySheep Dec 08 '21 at 20:27
  • You call a function that creates a variable. Then you return a pointer to that variable. When the function ends the variable is destroyed. Now the pointer doesn't point anywhere. If you try to use it literally anything can happen: the program could crash. the compiler could just make up a number for the value of the variable, the computer could reboot, literally anything. – Jerry Jeremiah Dec 08 '21 at 20:28
  • [Can a local variable's memory be accessed outside its scope?](https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope) – Drew Dormann Dec 08 '21 at 20:29
  • If you want to understand what can happen when you do something that is undefined behaviour (like using a pointer that doesn't point anywhere) have a look at this: https://devblogs.microsoft.com/oldnewthing/20140627-00/?p=633 – Jerry Jeremiah Dec 08 '21 at 20:30

0 Answers0