0

I am learning cpp for a month now and I always thought that variables inside functions, initialized on the stack, cannot be accessed from outside the function scope. However this doesn't seem to be the case when I use a global pointer to a member of the function like in the following case:

#include <iostream>

void fun(void); int *pInt;

int main(int argc, char **argv) {

  pInt = 0;   
  fun();   
  std::cout << "*pInt = " << *pInt << std::endl;
  return 0; 
}

void fun(void) {   
  int a = 3;   
  pInt = &a; 
}

Compiling and running this doesn't produce any error and indeed prints out the expected result. Why is this happening? Isn't "a" suppose to get out of scope (and thus its value) after the function fun is out of scope?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
bergercookie
  • 2,542
  • 1
  • 30
  • 38
  • This is called a [dangling pointer](https://en.wikipedia.org/wiki/Dangling_pointer). See questions like [this](http://stackoverflow.com/questions/35877487/dangling-pointer-is-still-accessing-the-memory-value) which are already answered on SO. – R_Kapp Apr 13 '16 at 20:20
  • 1
    The compiler doesn't produce code that intentionally destroys the content of the memory pointed to by pInt, it's just that when a goes out of scope, all bets are off as to what will happen to the memory that pInt points to. Perhaps it will turn to garbage due to other operations that will overwrite it, perhaps it won't - however you should always assume that accessing this memory will not give you what you expect. – Amnon Apr 13 '16 at 20:29

1 Answers1

0

No, what you're seeing is undefined behavior.

Once the fun() function finishes execution, a cease to exist. So, in the main(), any attempt to dereference the pointer, (earlier) pointing to the memory location for a, will invoke UB.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261