Pointer pointing to itself C

I am writing a function called at the end of a recursive chain. This function should determine where it is in memory when it is called. The code is as follows:

void recover () { int * x = (int *)&x; } 

The problem is that the program simply skips over this statement as if it had never been written. I checked this in GDP. Can you think of any reason why this line is ignored?

Thanks!

+6
source share
3 answers

Declare the variable as volatile . It should prevent compiler optimization.

 volatile int * x = (int *)&x; 
+8
source

If you compile with optimization enabled, this code is probably optimized due to the lack of effect for the program. Use the -O0 option.

+6
source

The code you wrote is probably undefined behavior, since you are placing a pointer to a pointer to an int pointer to a pointer to an int .

A pointer cannot conceptually point to itself, since you can never reach the desired level of indirection. That'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, void* is the only type of pointer that I can think of that may be allowed to violate this rule, but I'm not sure if it will be legal according to the standard.

I suggest you write the following instead of what you have:

 int* recover () { int local = 0; return &local; } 

And compile it without optimizations like @ysap.

It still seems from your example that you are trying to figure out where the top of the stack is, and this is very easy to do in the assembly. All you have to do is read the stack pointer. However, this is not so cleanly shown in C. Although GCC has some helper functions for similar tasks, I did not find them for the stack pointer.

I personally would have resorted to the built-in assembly, because everything that is written will probably not be portable anyway.

Also, if I understand your question correctly, this is most likely a duplicate of this question , so it will also pay for reading these answers.

Edit: It should be equivalent to returning the frame address of the current function, which can be performed using the GCC Built-in Function __builtin_frame_address (unsigned int level) , previously linked . The code will look like this:

 int* recover() { return (int*)__builtin_frame_address(0); } 
+4
source

All Articles