News for hackers. Stuff that matters.
Re:Undefined behavior in C is a reading error by cperciva on Thursday May 20, 2021 @03:55PM (#27226289)
The C standard says very little about how those types work. In particular, you can cast a pointer to one of them and then cast back to a pointer -- but only if you cast the exact same value back, and the intptr values are not guaranteed to be in any way meaningful.

In particular, casting a pointer to intptr_t, doing arithmetic on it, and casting back is not guaranteed to do anything useful. It almost certainly will, since most systems treat it as roughly the same as casting to char *, but the standard does not guarantee it.

Re:Undefined behavior in C is a reading error by Joker_vD on Friday May 21, 2021 @07:00AM (#27232522)
> and casting back is not guaranteed to do anything useful

I believe it's implementation-specific, precisely so that malloc/free can be implemented in conformant C.

The only tricky part is how you can "bless" parts of large memory block originally pointed to by void* (returned from mmap(), for example) to safely become ints and char[]s and structs...

Re:Undefined behavior in C is a reading error by magnostherobot on Thursday May 20, 2021 @04:04PM (#27226423)
Do you have an example of a situation in which you'd want to cast the result of arithmetic intptr_t values to a pointer? The situations I can think of off the top of my head would be better done as arithmetic between pointers.
Re:Undefined behavior in C is a reading error by bonzini on Thursday May 20, 2021 @04:18PM (#27226627)
Arithmetic on pointers in turn is only defined if the pointers point within the same object (or right past the end of that object).

One example of using intptr_t would be going from a pointer passed to free() to a metadata block for the memory that must be freed.