Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are Pointers stable?

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

like image 899
mfc Avatar asked Apr 07 '12 02:04

mfc


3 Answers

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.

like image 112
jimw Avatar answered Sep 20 '22 13:09

jimw


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.

like image 31
R.. GitHub STOP HELPING ICE Avatar answered Sep 17 '22 13:09

R.. GitHub STOP HELPING ICE


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.

like image 33
josephthomas Avatar answered Sep 18 '22 13:09

josephthomas