0
#include<stdio.h>
#include<stdlib.h>
int *p;
void f()
{
    int a=5;
    p=&a;
    printf("%d ",*p);
}
void main()
{
    f();
    printf("%d",*p);
}

Why the O/P is 5 5? After the function call is over then the local variable a is removed. So p should be pointing to invalid object

  • 1
    Because undefined behaviour is not guaranteed to go wrong. What happens is undefined, but it happened to work. If you insert another function call between `f();` and `printf("%d",*p);` you might get a different result. – Weather Vane Feb 25 '20 at 11:37
  • 1
    After returning from a function, C does not waste time initializing local data; it just leaves as it is. But keep in mind that; when the function is in scope, its data (the memory space that belongs to the function) is protected against being overwritten. When the code pointer hits the `return` line of the function however, all the memory space is left as it is but very susceptible to be overwritten (not protected any more). After returning from function, `main` may or may not print `5`, depending on the local memory being overwritten or not. – ssd Feb 25 '20 at 11:52
  • @aditi19 If you do not understand a certain phrase of [my answer](https://stackoverflow.com/a/60393887/12139179), please let me know to improve it. – RobertS supports Monica Cellio Feb 27 '20 at 08:35
  • understood... thanks – aditi19 Feb 27 '20 at 12:36

2 Answers2

1

If it is undefined behavior then it is also allowed to (occasionally) give the output of 5. But don't be surprised if the next morning it gives out 6.

mike3996
  • 17,047
  • 9
  • 64
  • 80
1

Why is the Output 5 5?

It is because of something called "Undefined Behavior". Undefined Behavior do not have to always provide the wrong result.

After the function call is over then the local variable a is removed. So p should be pointing to invalid object.

Exactly, it is pointing to an invalid object or better said to no object at all - the int object of a allocated inside of the function f() is already deallocated at the point of executing printf("%d",*p); in main().

To dereference a pointer with an stored address to an no longer existant object is Undefined Behavior.

It could print out anything. That it print out 5 is just a lucky shot, but never reliable. Even when executing the exact same file a second time, you already could get a different result.