I want to use the actual pointer address (not marked volatile) to an object to uniquely identify the object.
Is this a bad thing to do? In general does system memory management move the objects and hence it's address about or is the pointer stable?
Thanks
Your pointer is guaranteed to remain stable for the life of the object to which it points, unless you do something to break it. The OS does indeed move things around in memory, but that's physical memory - the virtual memory space the OS presents to your process will keep things at the same addresses.
In C, the address of an object is constant for its lifetime. Note that per the C standard, realloc
does not "move" an object; it allocates a new object with the same contents (for the shorter of the old and new length) and, if successful, frees the old object.
Pointers are stable, however, you should be using pointers correctly other wise you code will be unstable.
A pointer will be valid until the moment an object dies, once an object dies then you will have what is known as a Dangling Pointer.
There are many ways to avoid dangling pointers, some of them are very advanced topics. For example, you could use "Handles" but that is more sophisticated approach and would require a different memory management than what is default.
The language you are using also matters for the way a pointer can be invalidated. You have your question tagged as C, C++ and Objective-C. In C, your pointer can be invalidated by a malloc and realloc, where in C++ your pointer can be invalidated by delete.
I highly suggest reading more on pointers if you are first being introduced, such as this article.
I also suggest reading more into std::shared_ptr.
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