I am reviewing the code for a garbage collection system on my project and I was wondering -- is it acceptable to use a pointer as a unique internal hash or ID given that it holds the value of an address to a block of memory allocated by new
or malloc/calloc/realloc
? I only care about this property in order to quickly check whether a piece of memory is contained within a heap or list of pointers.
Asked
Active
Viewed 77 times
1

CinchBlue
- 6,046
- 1
- 27
- 58
-
1An address of a storage is unique, isn't it? It has usually "machine word width". Hence, this is IMHO a good choice to key things (i.e. objects). Of course, it should be a valid address (no dangling pointer thing), and this holds per process only. Separate processes may have equal addresses for different things due to [virtual address space](https://en.wikipedia.org/wiki/Virtual_address_space). – Scheff's Cat Mar 27 '18 at 09:29
-
Also, please, note what I found in cppreference about [`std::less`](http://en.cppreference.com/w/cpp/utility/functional/less): _A specialization of std::less for any pointer type yields a strict total order, even if the built-in operator< does not._ – Scheff's Cat Mar 27 '18 at 09:31
-
@Scheff I was also wondering whether strict aliasing would have any interaction with this problem. – CinchBlue Mar 27 '18 at 09:43
-
Remember that an address is only unique in _space_ and not in _time_. This is a fancy way of saying that addresses can be reused for completely different objects as long as their lifetimes don't overlap. Whilst this may sound obvious there's a number of subtle and annoying bugs that can fall out of not getting this exactly right - see for example the _infamous_ [ABA](https://en.wikipedia.org/wiki/ABA_problem) problem in lockfree programming. So make sure your system doesnt consider address' which are or may've been free'd. – Mike Vine Mar 27 '18 at 09:49
-
I just recalled [SO: What is the strict aliasing rule?](https://stackoverflow.com/a/99010/7478597). IMHO, if you just use the address of an object as key - this is not an aliasing problem as described in the link. Things might change if you want to use the key as pointer again - especially if the key type is not the original pointer type, but that's something different. – Scheff's Cat Mar 27 '18 at 10:06
-
Just be careful when it comes time to hash the pointer value, or otherwise convert it to a key. It's probably safest to treat the pointer value as a blob o' bytes, of size `sizeof(whatever *)`. It can be risky to assign or cast a pointer value to an integral type, and of course it's basically ruinious to assign or convert one to a plain `int`. – Steve Summit Mar 27 '18 at 11:07