-1
#include <stdio.h>

void func(int **z)
{
    int q = 10; /* Local variable */ 
    *z = &q;
}
int main()
{
    int a = 100;
    int *p = &a;
    printf("%d\n", *p);
    func(&p);
    /* dereferencing pointer with func() local variable 'q' address */
    printf("%d\n", *p);                       
    getchar();
    printf("exit");
}

In the above code local variable is accessed in main() even though stack for local variable is collapsed. I was expecting a Core Dump/Segmentation fault. But it not happening in this scenario.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
Pavan
  • 1
  • 1
  • 3
    Welcome to the wonderful world of undefined behavior. Which sometimes includes "appearing to work". – Shawn Mar 31 '20 at 07:21
  • 1
    Does this answer your question? [Local variable still exists after function returns](https://stackoverflow.com/questions/12901383/local-variable-still-exists-after-function-returns) – Karthick Mar 31 '20 at 07:25
  • Read [this](https://stackoverflow.com/questions/6441218/can-a-local-variables-memory-be-accessed-outside-its-scope/6445794#6445794). – Jabberwocky Mar 31 '20 at 07:39

2 Answers2

1

You are not accessing the local variable but it's memory address. Although int q went out of scope, it's address is still accessible if you have a pointer pointing to it.

In your function you use a pointer(z) to point to the pointer p address and then in line "*z = &q;" you are placing the variable q address in your p pointer. So when q goes out of scope then you call printf("%d\n", *p); and you can still see the contents of your out of scope q variable. Hope this helps!

Windfish
  • 68
  • 7
  • Yep and as hanie answered bellow you shouldn't be accessing out of scope variables. It could cause Undefined behavior. e.g. The 4 byte memory of your int q could be allocated as part of an 8 byte string further down your program (or any other variable). Now not only will that memory be altered into something new but trying to read that int*p will result in your program trying to interpret a 4 bytes of a string into an int! – Windfish Apr 01 '20 at 03:58
0

When the scope of a variable end and it's stack is collapsed, accessing it and it's variables is wrong , and will cause Undefined behavior ,which you can never predict and could lead to crash or change in your program.

hanie
  • 1,863
  • 3
  • 9
  • 19