The code you wrote is probably undefined behavior since you're casting a pointer to a pointer to an int
to a pointer to an int
.
A pointer can't conceptually point to itself since you would never be able to achieve the right level of indirection. Here's why:
Declaration | Type | Type after using the & operator
--------------------------------------------------------------
int x; | int | &x is an (int*)
int* x; | int * | &x is an (int**)
int** x; | int ** | &x is an (int***)
However, a void*
is the only type of pointer I can think of that might be allowed to break this rule, but I'm not sure if it would be legal according to the standard.
I would propose you write the following instead of what you have:
int* recover ()
{
int local = 0;
return &local;
}
And compile it with no optimizations like @ysap suggests.
Still from your example it seems like you're trying to figure out where the top of the stack is and that is very easily done in assembly. All you need to do is read the stack pointer. However, this isn't so cleanly exposed in C. Though GCC does have some helper functions for similar tasks I haven't found one for the stack pointer.
I would personally resort to inline assembly since whatever is written will probably not be portable anyway.
Additionally, if I'm understanding your question right it is most likely a duplicate of this question so it would pay to read those answers as well.
Edit: It should be equivalent to return the address of the frame of the current function which can be done by using a GCC builtin function __builtin_frame_address (unsigned int level)
linked earlier. The code would look like this:
int* recover()
{
return (int*)__builtin_frame_address(0);
}