I write a function f() to return local pointer to main function. I know the memory of f() function will be released after it execute. However the f() function can return the pointer which point the array of a[2]. I think a[2] should be released, but it still exist.
So I want to know can I write a function which can return the local pointer and the local pointer point the local variable in the function? If it can return, why array of a[2] would not be released after the end of f() function?
#include <stdio.h>
int* f()
{
int a[2] = {1, 2};
int* p = a;
printf("%p\n", p);
return p;
}
int main(void)
{
int* p = f();
printf("%p\n", p);
return 0;
}
Since the array you point to will go out of scope and cease to exist, attempting to dereference the returned pointer will lead to undefined behavior.
However, in practice the memory will still exist, and if none of the contents have been overwritten by later function calls, it will still be there unmodified. So if you attempt to dereference the pointer you will still see the data. But you should not do that!
Regarding what you're doing, you're not actually dereferencing the pointer, so you don't have UB. All you're doing is printing the value of the pointer itself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With