-1

What is the problem associated with returning a pointer to a local variable?

And (i don't know if its legal to do this) What is the problem with returning a reference to pointer in main? ex:

int *p;
p=abc();

where abc would be returning int&

P.S. Sorry if not clear. I am confused too :P

Barmar
  • 741,623
  • 53
  • 500
  • 612
Raghav Sharma
  • 109
  • 1
  • 1
  • 6
  • If the return type of `abc` is `int&` – that is, *reference* to `int` – then the above assignment is a type error. Did you probably meant `int *`, aka *pointer* to `int`? – 5gon12eder Sep 11 '14 at 22:35

3 Answers3

1

You can syntactically return a pointer to a local variable, but that variable will no longer be valid after the function has returned.

Mark Harrison
  • 297,451
  • 125
  • 333
  • 465
1

If your code is:

int *abc() {
    int n = 3;
    return &n;
}

void foo() {
    int m = 4;
}

int main() {
    int *p;
    p=abc();
    foo();
    printf("%d", *p);
}

then m will probably overwrite n and the result will be 4.

Elad
  • 633
  • 5
  • 13
0

In simple terms, local variables are available only as long as it is in that function is in the function stack, once the function is done, its popped out of the function stack.

resultsway
  • 12,299
  • 7
  • 36
  • 43