Can a pointer ever point to itself?

前端 未结 8 908
情深已故
情深已故 2020-12-04 15:29

My question is: If a pointer variable has the same address as its value, is it really pointing to itself?

For example - in the following piece of c

8条回答
  •  悲哀的现实
    2020-12-04 16:00

    Yes, a pointer can point to itself as mentioned in the answers.

    A possible use case is we can use this trick in lieu of NULL pointers. You can initialize int * p = (int *)&p, and check this later to see if the pointer is valid or not. This could have been used if say in a system where we wanted 0x0 and the entire address range to be valid addresses.

    You can also use this trick in special C programs which would not crash on NULL pointer usage because you would avoid them altogether and on dereference system will not crash. It will lead to erroneous behavior but it may help debugging in certain situations.

提交回复
热议问题