What's the difference between an integer and a pointer? (2018)
Modern C compilers optimize code based on pointer provenance rather than raw integer values, meaning pointer-to-integer casts can cause unexpected compiler behaviors.
read it The post provides a clear, code-backed illustration of why treating pointers as mere integers causes subtle compiler bugs.
summary
Systems programming languages face a fundamental conflict between high-level alias optimizations and low-level pointer manipulation. A crafted C code example demonstrates that Clang and GCC handle integer-to-pointer roundtripping differently depending on whether an address was derived through direct observation or calculation. This divergence occurs because modern compilers track pointer provenance rather than treating pointers as raw bitvectors. The accompanying discussion explores how languages like Rust and hardware like CHERI enforce strict provenance rules.
key points
- Modern optimizing compilers use pointer provenance tracking, meaning pointers carry hidden metadata about their origin that raw integers lack.
- C and C++ standards provide sparse guidance on integer-to-pointer roundtripping, leaving compiler writers to balance optimization safety and developer expectations.
- Hardware architectures like CHERI and languages like Rust demonstrate a growing industry shift toward formalizing strict pointer provenance rules.
who should read it
Systems programmers and compiler engineers interested in low-level memory models and optimization edge cases.
discussion positive
consensus
Most participants agree that treating pointers as plain integers violates the abstract machine model and breaks on architectures utilizing tagged memory.
pushback
Some argue that on standard flat memory architectures, pointers and integers remain interchangeable in practical use.
The argument that this is valid defined C is not entirely correct. You can not subtract one pointer form another that doesn't come from the same allocation, that is explicitly UB. But the user here subtracts one integer from the other and that is valid. However C only guarantees you can you can convert a integer to a valid pointer, if that integer has been converted from a pointer, and not been modified in any way. If the integer has been modified its implementation defined what happens. Its no longer valid standard C.
C supports pointers that can have memory banks, or pointers that are …
Clarifies how hardware architectures like CHERI rely on memory tags and metadata, proving pointers are fundamentally different from integers.
Generated by an LLM from the article and thread. Check the sources before relying on it.