Why can I access a pointer declared in a function when I'm trying to access it from outside the function in c language?

Viewed 77

Happy new year everyone.

I am studying C language. I had a question when some code run about pointer.

#include <stdio.h>

int * b() {
    int a = 8;
    int *p = &a;
    printf("the addr of a in b: %p\n", p); the addr of a in b: 0x7ffccfcba984
    return p;
}

int main () {
    
   int *c = b();
   printf("the addr of a in main: %p\n", c); // the addr of a in main: 0x7ffccfcba984
   printf("The value of ptr is : %d\n", *c ); // 8
   
   return 0;
}

Can you feel something odd in this code?

I learned that a variables declared inside a function is deallocated at the end of the function. However, I can still access variables outside the function like above code when trying to access the address of "a" variable. If the deallocation is true, int a should be deallocated at the end of the b function. It is like a free is not used after variables is declared. Is there some knowledge I am missing about deallocation? Could you tell me why I can still access it?

2 Answers

Once you leave a function variables "fall out of scope" meaning they are no longer valid.

Using the address of an out of scope variable breaks that boundary and leads to undefined behaviour, as in, it's not valid to do. The &a pointer is effectively invalidated when you exit that function. If you use it then the program may behave erratically, might crash, or might work fine. It's not defined what happens.

In this trivial example you're not going to get the same behaviour as in a real program. Make another function call to a function that exercises the stack and you'll likely see some problems since the stack is being re-used.

Local variables aren't "allocated" per-se, they are simply scoped, and when that scope is exited they are invalidated.

In something like C++ there may be a deallocation process when things fall out of scope, as that language can define destructors and such, but that's not the same as C. In C they just cease to exist.

I learned that a variables declared inside a function is deallocated at the end of the function.

If the deallocation is true, int a should be deallocated at the end of the b function.

Yes. You are not wrong.

A variable will be destructured when it goes out of its scope. Although you use a pointer variable to save a pointer to that variable, accessing it through that pointer is actually an undefined behavior.

Yes, you can access it and see the results you expect because of luck or environment, but it may still cause a crash, unexpected results, etc. Because this behavior is undefined and wrong.

Related