Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

> all of the tricks which make "malloc" work,

What are those, exactly? AFAIK, you can safely track memory addresses by storing them as intptr_t/uintptr_t.



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.


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


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.


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.


Oh, for instance, on some implementations there is a lot of interesting stuff just prior to the allocated block returned. Not exactly the pinnacle of elegance but it gets the job done.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: