Search code examples
c++pointerspointer-arithmetic

Which dummy pointer values are okay


This is something that's been on my mind for a long time. Every once so often i see people use 1, or -1 as a dummy value for a pointer. To safe the need of a different variable.

Is it okay to use pointers like this? I suppose -1 is okay. But is it also okay to use other negative numbers? And can I be sure 1 isn't a used memory location? And if so, up to which value can i use memory pointers.

P.s. I'm aware storing other data especially positive values in pointers, is very, very bad practice. But I'm just wondering what would be the consequences in any real life situation.


Solution

  • It depends on your compiler and (mostly) OS -- on most operating systems there are ranges of addresses that can never be valid. So on such an OS, it is safe to use such addresses as 'magic' values for a pointer that will never compare as equal to any valid object. As long as you never dereference them they should be fine -- and even if you do dereference it, the OS may define the behavior (generally throwing a particular signal).

    A more portable alternative is to create 'dummy' global objects and use pointers to them as your special tags. No other valid object pointer will ever compare as equal to the dummy object pointer, and the extra overhead for the dummy object is minimal.