Hacker News new | ask | show | jobs
by sparkie 10 days ago
The standard is quite specific about what occurs when casting between integers and pointers.

> An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, may not be correctly aligned, may not point to an entity of the referenced type, and can produce an indeterminate representation when stored into an object.

> Any pointer type may be converted to an integer type. Except as previously specified, the result is implementation-defined. If the result cannot be represented in the integer type, the behavior is undefined. The result is not required to be in the range of values of any integer type.

Why would these passages be written with such specificity, only to be overridden by unwritten passages w.r.t intptr_t?

When intptr_t was added, for C99, segmented memory was not uncommon, and there was more variation in processor architecture. The reason this is IDB or UB is because there were architectures where the implementation of such conversions is not straightforward.

Today we've largely converged on a common model of a single virtual address space with paging - if it were written today, it probably would have included such clauses, or made more assumptions about conversion between int/pointer rather than explicitly stating that nearly all behavior in this regard is IDB or UB, because the architectures these clauses were written to address - where implementation is non-obvious - are pretty much obsolete.

Anything besides this is subjective "interpretation" of the spec. There's nothing about `intptr_t` having different properties - the intptr_t is sufficiently wide to hold a pointer converted to integer - it solves only the last issue that "the result is not required to fit in the range of values of any integer type" - and hence why `intptr_t` is optional. It says nowhere that its purpose is to ensure that an intptr_t converted back to can be dereferenced without IDB. It's a pointer converted from an integer which is still subject to the constraints specified for int->pointer and pointer->int conversion.

Again, I don't challenge the idea that `void*->intptr_t->void*` is intended to result in a usable pointer - but I reject the idea that it was some kind of oversight to not explicitly state it in the spec - when the spec explicitly states the opposite - that it's IDB. It's implementation-defined because it was intended to be used in such way where pointers are effectively integers, but they did not want to place constraints on compilers which targetted the other architectures where making this guarantee would've been unpractical.