1

Here is the simple code:

int *ad_return()
{
    int a=600;
    cout << &a << endl;
    return &a;
}

int main()
{
    cout << ad_return();
    return 0;
}

The output is unexpected. The first cout prints an address that looks like a address but the cout that is in the main prints a legit 0. I couldn't find an explanation anywhere.

Thope
  • 49
  • 4

2 Answers2

3

Based on what I have experimented, I have concluded the following:

Since the address of a local variable that has already went out of scope is undefined, it seems that gcc and g++ decided to implement a feature that sets this to zero (probably to make sure that the code segfaults instead of generating thoroughly bizarre behaviour). It does not do this in clang, but the value is undefined so both of these compilers are operating in accordance with the standard.

Leonid
  • 708
  • 5
  • 12
  • 1
    You can see the relevant code in gcc [here](https://github.com/gcc-mirror/gcc/blob/ae6fc5ce43788db6962ca657e8c0d17017c1a6e2/gcc/gimple-ssa-isolate-paths.c#L781). There's an interesting mention that such a function *could* be legal if the return value is never used by the caller; otherwise they would have inserted code to crash the program then and there. – Nate Eldredge Apr 12 '20 at 13:32
0

Try This Code.
There was problem you were trying to access address of a local variable a it is not accessible out side of the function as_return(). So declare it in global so that it is accessible to everyone.

   #include<iostream>
  using namespace std;
  int a;
  int *ad_return()
  {
   a=600;
   cout << &a << endl;
   return &a;
  }

  int main()
  {
   cout << ad_return();
   return 0;
   }

.
Output Screen

I hope you got answer

Ankit Mishra
  • 530
  • 8
  • 16