Explanation for the output of the code

278 views Asked by At
#include<stdio.h>
int *call();
int main()
{
    int *ptr;
    ptr=call();
    fflush(stdin);
    printf("%d",*ptr);
    return 0;
}
int * call()
{
    int x=25;
    ++x;
    return &x;
}

The output for this code is 0. I was expecting 26.
Can someone please explain the reason?
And what should I be doing to get 26?

3

There are 3 answers

0
user2736738 On BEST ANSWER

When you create this function and call it a function frame is pushed into the stack having a space for a int variable declared there. Now you increase the value and try to return address of that. Now function ends and stack frame is deleted. You are trying to read it. It will return something random. Ah not random in its sense but what it returns is not defined. You get 0 ..may get 1 or 23 or 128749 or -7364184 sometimes.

To get 26 you might want to use something from heap.(or declare an array which will be alive long enough). Allocate memory big enough to hold an integer variable. Then manipulate it. Return pointer to that . You will see what you want to see.

Note: It's undefined behavior.... it may return something else when you run at different time or different machine. :)

This heap and stack that I mentioned here are implementation specific. By heap I mean the dynamic memory which we allocate.

0
Sourav Ghosh On

The problem here is, from int * call(), you're returning the address of a local variable, which becomes invalid after the function has finished execution. Using the return value invokes undefined behavior.

You should either

  • take a pointer, allocate memory using memory allocator functions like malloc() and family and then return the pointer.
  • make use of a static variable whole lifetime is throughout the program execution.

That said, do not use fflush(stdin), as it invokes undefined behaviour. Quoting C11, chapter ยง7.21.5.2, (emphasis mine)

If stream points to an output stream or an update stream in which the most recent operation was not input, the fflush function causes any unwritten data for that stream to be delivered to the host environment to be written to the file; otherwise, the behavior is undefined.

4
akhileshmoghe On

You should not use fflush() on stdin, it has undefined behaviour for input streams. You can Read about it here.

Returning the address of a local variable, which becomes invalid after the function has finished execution will result in Undefined Behaviour.

In expectation of answer, I removed fflush(stdin) and got output 26 on both Windows and GCC 4.1.2 compilers.

As commented by @Anjaneyulu, it may be compiler dependent too, but here's screenshot from my test on windows.

enter image description here