Stealing bits from a pointer

In the art of multiprocessing programming, p215, authors say that in C you can “steal” a bit from a pointer, and using bitwise operators extracts some flag (label) and pointer from a single word, I don’t know how to do this, so the example will help me .

+7
c pointers bit-manipulation
source share
2 answers

Imagine a system with a 32-bit pointer size, but only 1 GB of memory is available. Addressing the entire memory space requires only 30 bits, so the upper 2 bits are not used. You can use these two upper bits for your purposes - for example, for marking pointers by pointer type (stack / global or dynamic).

Please note that the code you get as a result is not as portable as it is. You should be familiar with the processor your code is running on - in particular, you need to know whether the high bits will be deleted when the address from the pointer is sent to the address bus.

+8
source share
  • Make sure the pointer objects are aligned in memory, so that all of your pointers are even numbers. The last bit is then free to hold one Boolean flag. (This cannot be done completely portable, so you need to know about the platform.)

  • Move the pointers around as integers of type uintptr_t . They can be easily manipulated:

     bool get_flag(uintptr_t p) { return p & 1; } void *get_pointer(uintptr_t p) { return (void *)(p & (UINTPTR_MAX ^ 1)); } uintptr_t set_flag(uintptr_t p, bool value) { return (p & (UINTPTR_MAX ^ 1)) | value; } 
+8
source share

All Articles