-1

I've a question about var scopes and pointer. That's an example function:

int *double(int a)
{
    int p = a*2;
    int *ret = &p;

    return ret;
}

And that's the question: After a fuction return to the caller, it should delete from the memory every variable declared in it.

In this function I only return the addres of "p" (that's declared only in the function) but when I use it in the main, for example, the space of memory allocated by the function "double" hasn't been deleted.

Why?

Roberto Aureli
  • 1,428
  • 2
  • 12
  • 23
  • Because `p`  is on the stack and only exists in the function. It have been deleted, what you are seing is probably just the leftover value that is considered invalid. Using it is undefined behavior – litelite Aug 28 '17 at 15:58
  • how do you know it hasnt been deleted? – pm100 Aug 28 '17 at 15:59
  • No, I said that it exists even in the main when I access it by the address that my function returns. – Roberto Aureli Aug 28 '17 at 15:59
  • This is UB afaik. It may or may not have been overwritten by the time you access it. Returning an address to a stack allocated variable should never be done. – Carcigenicate Aug 28 '17 at 15:59
  • No, because **undefined behavior** is *undefined*. `p` doesn't exist any more, but there's no obligation that your program changes whatever valuae is stored there. It could be overwritten any time by something different. –  Aug 28 '17 at 16:00
  • 1
    Good, so the function release that part of memory but it's possible that no one write over it – Roberto Aureli Aug 28 '17 at 16:01
  • https://stackoverflow.com/questions/13415321/difference-between-static-auto-global-and-local-variable-in-the-context-of-c-a – fukanchik Aug 28 '17 at 16:01
  • Sorry for the C++ dupe, but it's just a perfect match (with a great answer over there) –  Aug 28 '17 at 16:04
  • Obv that's not a problem, thank you! – Roberto Aureli Aug 28 '17 at 16:05

1 Answers1

1

The memory isn't valid anymore; what happens when you access it after double has returned is undefined behavior. That means that anything is possible:

  1. It could be that the value hasn't been overwritten by something else yet (what likely happened in your case).

  2. It could be that something else has written something to that address, so the value is now random garbage.

  3. It could be that your code opens up a wormhole to a parallel dimension, causing an invasion of evil space octopi that dooms us all.

So, basically, I don't recommend it.

Charles Srstka
  • 16,665
  • 3
  • 34
  • 60