简体   繁体   中英

How to properly store extra data in LSB pointer bits?

I have a GSList from GTK/glib 2, and those only store full pointers, and I really don't want extra allocations. How do I do bit twiddling hacks to store extra data in those pointers?

I figure I can't just take a pointer and do tagged_ptr = ptr | 1 tagged_ptr = ptr | 1 (indeed, the compiler complains very loudly when I try). I'm not sure how to do this.

This would definitely be local to a single function, however, and the GSList (or the pointers) would not leak onto the rest of the code.

To perform arithmetic on the numeric value of pointers (as opposed to pointer arithmetic , which is different and highly constrained), you need to cast back and forth to an appropriate integer type. If stdint.h defines UINTPTR_MAX , the appropriate type to use is uintptr_t . If not, there is no appropriate type, and your (nonportable) hack can't work on that particular implementation.

Note that you also have the problem that you're assuming pointers have low unused bits. If _Alignof(max_align_t) is greater than 1, this is probably a reasonable assumption, assuming the implementation follows the intent of the standard that the transformation to uintptr_t reflect the address model of the implementation (rather than being some arbitrary injection). But if not, you're out of luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM