Hacker News new | ask | show | jobs
by cowlevel 10 days ago
> When casting from pointer to integer and back again, the resulting pointer must reference the same object as the original pointer, otherwise the behavior is undefined.

So I'm right. This is implementation-defined, and the way the implementation has defined it is to make it fully UB (except for round trips).

1 comments

Whenever something is undefined behaviour or not is a matter of the standard and what the implementation may or may not have defined for that is immaterial to that. As far as the standard is considered, when they encounter UB, you no longer have a valid C program. However the compiler can still choose to do something with it, which in this particular case manifests as GCC has documented it, but some other compiler can do something else for it.
You have it backwards, the language document says it's IDB and the ID has chosen to make it UB.
Good point, I misremembered that. I have read the standard, but it seems that they changed some of the language around between C17 and C23. In C17 (6.3.2.3 Pointers), we have:

> 5 An integer may be converted to any pointer type. Except as previously specified, the result is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation.68)

> 6 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 need not be in the range of values of any integer type.

And in C23 (6.3.2.3):

> 5 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.58)

> 6 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.

It's interesting that they dropped the "trap representation" language from C23. Of course, being an "indeterminate representation" probably does the same thing given that "trap representation" isn't a thing in C23 at all.

But yeah, I was wrong about the pointer roundtrip.