quelsolaar 2 hours ago

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 consist of a hash and and an offset. Real world hardware architectures like CHERI does this and standard C supports this. In hardware like that, this would break, even if the subtraction is done on integers, and don't violate the no subtraction of pointer of different allocation rule. So no, Pointers are really not integers, even if they may look like integers on your machine.

E (Member of the wg14 memory model study group.)

  • dapperdrake 2 hours ago

    There are also Harvard architecture machines like microcontrollers where a function pointer points to ROM and a data pointer points to RAM.

    Feels a little like Harvard architecture says there is not global axiom of choice and von Neuman architecture and single tape Turing machines explicitly count everything in the same memory (except for the logic in the Turing machine control head.)

  • sparkie 2 hours ago

    If you convert a pointer to `intptr_t`/`uintptr_t` and back again to a pointer, the standard only guarantees that it compares equal to the original - but it makes no guarantee that you can dereference that pointer.

    For example, if you had a system with segmented memory, you could cast a pointer used in one segment to `intptr_t`, change the segment register, then attempt to cast back to a pointer and dereference it, which of course is UB.

    Pointers are not merely bit vectors. Their representation depends on architecture, and there's no guarantee that they even have an integer representation (intptr_t/uintptr_t are optional) - and even if they do have an integer representation, there's no guarantee that this is a complete enough representation to use the pointer - eg, with the segmentation example above - the `intptr_t` does not contain the segment information.

    The examples work as one would expect because they're being run on a system with a single linear virtual address space, where pointers can be represented by an integer. The compiler for such platforms may specify what behavior is to occur in these cases - but the C standard does not.

    • uecker 2 hours ago

      I hear this claim sometimes, but I think this is a far-fetched interpretation that you can only compare the pointers after backconversion but not use them.

      A segmented architecture that can not support this should not support intptr_t. It is optional for this reason.

      • sparkie 1 hour ago

        The C standard does not make any guarantees that you can dereference it.

        And x86-64 is arguably still "segmented" in that you can use the FS and GC segment registers (they're typically used for TLS). Eg, if you cast a `thread_local` pointer to `intptr_t` - the standard makes no requirement that it point to the absolute virtual address (though this is the common implementation choice by GCC etc).

        • uecker 1 hour ago

          The standard is English text which may not alway be perfectly precise, but the wording there clearly was meant to allow this.

          • sparkie 1 hour ago

            I think it's quite clear.

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

            That isn't to say we can't do the cast - compilers specify the behavior, and most modern architectures have a linear virtual address space where the round trip is valid - though it may not always be - for example, with the fs/gs segment registers - a cast of pointer to integer isn't just a simple conversion of type - it must also fetch the value from the FS register and offset the pointer by this to produce an integer containing the absolute address. This is entirely implementation defined.

            Producing the absolute virtual address of a `thread_local` is potential UB though - if you attempt to dereference it in a different thread.

            Another example would be casting a qualified pointer (const, restrict, volatile) to an integer, then back to a pointer with a different qualifier or no qualifier - then dereferencing such pointer would of course be UB as per the standard - the cast to `intptr_t` loses information about its qualification - but the pointers would still compare equal - as the standard guarantees that a pointer cast to a qualified pointer compares equal.

            • uecker 1 hour ago

              There are stricter requirements for casting a void pointer to (u)intptr_t and back. Again, a segmented architecture should not provide (u)intptr_t. But if an implementation has it, in my opinion, this is expected to work.

              • sparkie 1 hour ago

                The only stricter requirement in the standard is that they compare equal after the round trip.

                The intended purpose of these types is to allow the round trip, yes, and the requirement they compare equal is part of that. The standard doesn't put stricter requirements. I don't think that is an oversight, but a deliberate omission to allow for flexibility in implementation.

                It's up to the compiler to specify that it's safe to dereference the pointer after the round trip - the standard does not want to put such constraints on implementors.

                • uecker 1 hour ago

                  This is where I disagree. In the context when this was written, I think it was clear that two pointers that compare equally were meant to be interchangeable.

                  • sparkie 39 minutes ago

                    It would've been trivial for the committee to add such clause in the spec - why only the requirement that they compare equal and not that they dereference the same object?

                    The standard leaves a lot of things implementation defined deliberately to allow for flexibility in both processor design and compiler implementation.

                    I don't think for example, a segmented architecture shouldn't provide an `intptr_t` - it's still useful to be able to cast a pointer to integer and back even in the case of segmentation - but is obviously more prone to error if we dereference it in a different segment (which would be UB).

                    I completely agree that it is the intended case that a pointer that has had this round trip is intended to be dereferenced - but I disagree that the requirement to do so is an oversight and not a deliberate omission.

                    There are potential cases where you would want to dereference the pointer but to a different object (which is UB by the standard, but could be well defined for a specific compiler/arch). Consider for example, if you have a bunch of threads which all have the same structure in their thread local storage - it can be useful to be able to specify an offset that is going fetch a value specific value from the TLS - but obviously a different one in each thread - ie, we want the pointer to be an offset, and not an absolute address.

                    • uecker 18 minutes ago

                      It is not trivial for anything to be done in a committee. If we wrote this text today, we would clearly specify this differently, but in the 90s there was not much reason to assume that this will be misunderstood. Note also that the far / near pointer model used by segmented architectures was never part of ISO C.

                      The committee wanted to have TS 6010 which would clarify that this work, but at the request of compiler vendors it is not (yet) part of the IS. But the reasons are unrelated to pointer round trips.

        • leni536 1 hour ago

          FTR C++ makes the guarantee. I'm not familiar enough with C standard wording to comment on that.

  • afdbcreid 1 hour ago

    I'm not a C expert, however I do follow Rust's discussions about pointer provenance. It might be unspecified but people do rely on this (e.g. pointer tagging is the same under your explanation), and even CHERI uses hacks to not break them, at least whenever possible. Furthermore the standard says in a footnote:

    > The mapping functions for converting a pointer to an integer or an integer to a pointer are intended to be consistent with the addressing structure of the execution environment.

    So even if it's not mandatory, it is expected to work.

  • SkiFire13 1 hour ago

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

    The C standard doesn't even guarantee that. It only guarantees the conversion from 0 to a null pointer. Any other integer-to-pointer conversion is implementation defined.

    What implementations _want_ to define is a different question though.

  • OptionOfT 47 minutes ago

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

    How does that work when I want to set an address high?

    • quelsolaar 35 minutes ago

      You cant in standard C, but many implementations do let you manipulate pointers in all kinds ow ways, but then your code depends on an extension of the language and is not portable. C is designed so that you can write both portable and non portable code. I would argue you shouldn't because often these extensions are very poorly documented and are based mostly on "it seems to work". Try when possible to stay within the standard.

tialaramex 2 hours ago

Quite some time after this blog was written Aria blogged about the "strict provenance experiment" for Rust, and today Aria's API (more or less) is sanctioned and Rust is defined to deliver the behaviour Aria described in the Tower of Weakenings.

Here's the Rust documentation: https://doc.rust-lang.org/std/ptr/index.html#strict-provenan...

So in Rust much of this is spelled out today, although of course the LLVM backend still miscompiles some programs (in Rust or indeed in C or C++) because it can be tricked into giving integers provenance even though that's clearly not what anybody wanted. Oops.

However in C, which most of the examples are written in, the status is a bit less clear. Martin Uecker (who can often be found here in HN's comments) and colleagues wrote a document for ISO but that document is not (yet?) part of the ISO C standard itself. Of course in practice compilers like LLVM, GCC and MSVC need to do what the document says instead of making it up as they go, or else this matters very little.

One thing which cannot be in doubt in any of these close-to-the-metal languages today, almost certainly including obscure ones you've maybe taken a shine to like Odin or Hare, is that provenance is a thing, if you're sure you don't have pointer provenance in your languages but you do have actual pointers, check with a stop watch. If your programs in that language are very slow you might be right.

Because that's why this became a thing. Without provenance, pointers strangle many "obvious" optimisations. Add provenance and now these optimisations are available and your programs go much faster. It's a bargain - albeit one you probably never signed up for as a programmer.

  • uecker 1 hour ago

    Hey, that's me. TS 6010 is not currently supported by GCC and Clang. But also for Rust this does not work due to the same compiler issues. (as you point out)

    • afdbcreid 1 hour ago

      Do note though that strict provenance in Rust does work (at least we're not aware of any miscompilation AFAIK), and pre-strict-provenance semantics, or exposed provenance semantics, are warned against in the docs and clarify that they do not have accepted formal semantics. So the situation is a bit better than C.

      • uecker 1 hour ago

        Perhaps. In C one should avoid any non-local use of one-after pointers and any integer-to-pointers casts. Then I think one is also safe from miscompilation. Alternatively, one can use a compiler that is not broken.

        • tialaramex 42 minutes ago

          Do you have a particular suggestion of a "not broken" C compiler? Genuinely interested.

          • uecker 22 minutes ago

            No, not really. There are couple of smaller compiler projects such as tcc, slimcc, cparser, kefir, etc. that I kind of hope will mature a bit more, but I haven't really used them.

            Sometimes I am wondering whether I should continue to develop my own compiler with an eye towards correctness, but I do not have enough time at the moment. And fixing bugs in GCC seems more useful.

      • tialaramex 28 minutes ago

        It's true that Rust gives confidence to do (some) crazy pointer tricks which would work in the "pointers are just integers" world, yet not pay the performance price such tricks would cost if we really did "pointers are just integers"

        My favourite example is ColdString, a value the same size as a thin pointer and which could be pointing at some text on the heap - but for smaller texts it is actually inline UTF-8 encoded text, the author originally wrote this to rely on the scary Exposure rules and I asked them if it couldn't be Strict instead and instead of "If you're so smart why don't you do it then?" they just fixed it. Nice. Huge fan of ColdString.

        However, there are extant examples where you can just trick LLVM into asserting that two integers a,b are different and then showing that a - b == 0 which proves it was lying, those are by definition miscompilations and they don't rely on Exposure, they're just getting the LLVM optimiser to apply a pointer provenance optimisation to a thing it was just told is not a pointer.

  • afdbcreid 1 hour ago

    > However in C, which most of the examples are written in, the status is a bit less clear.

    I believe it's a bit of an exaggeration. Formally specifying int2ptr and ptr2int casts in a way that permits both all code found in the wild (or at least a large majority of it) and all optimizations compilers want to perform (ditto), is more than just a bit difficult.

andai 4 hours ago

Article says pointers and its are both just bitvectors, but doesn't explain what a bitvector is.

It seems to be a vector of bits? Except in practice, a bitvector is just an int where you're using the binary digits to store stuff? And you gotta use these awkward bitwise operators to actually use it? (Popular in 90s video games, to save RAM!)

Or was it another way of saying "ultimately it's the same pattern of ones and zeroes so you can do whatever you want with it as long as you know what you're doing" ?

  • amavect 3 hours ago

    >ultimately it's the same pattern of ones and zeroes

    Exactly. Much equivocation happens when talking about concepts and representation of those concepts. Numbers, bitvectors, pointers, ones-and-zeros, colors, characters, indices, enum values, and whatever all share the same representation. The author thought "bitvector" best represented the commonality (though it doesn't).

  • jeremyscanvic 2 hours ago

    It got me wondering so I checked. According to Wikipedia [1], it's a contiguous sequence of bits.

    I guess the point here is CPUs operate on groups of bits that are very localized spatially (physically).

    [1] https://en.wikipedia.org/wiki/Bit

  • mwhitfield 1 hour ago

    > Except in practice, a bitvector is just an int where you're using the binary digits to store stuff?

    I think he's trying to say it's just the opposite: an int is really "just" a bitvector, when it comes down to it, and you just happen to be using a constrained set of operations to emulate the behavior we expect of integers.

notorandit 3 hours ago

Assembly programmer here.

Depending upon the architecture, not all values can be memory addresses (aka pointers) due to alignment constraints. Then other way around is possible as long as memory addresses have at least l the same number of bits as integers.

Finally, as long as you don't dereference an integer used (casted) as a pointer, there is no difference. Like equality comparison.

  • afdbcreid 1 hour ago

    Assembly indeed has a very easy exit in such issues (and in UB in general).

dapperdrake 2 hours ago

There was an old VAX or something that had a C standard library where function pointers in both C and Fortran were multiple machine words. C was 4 words and Fortran was 6 with everything but the first two being reserved for later. The idea was to provide additional argument and return type information in tag bits in the additional machine words.

So, mathematically, pointers still are integers, because "everything" can be encoded as a natural number. Handles like in Windows or UEFI, hardware descriptors like internal to netmap and io_uring for NIC physical memory mapped control registers, 32-bit integer page numbers within sqlite databases, or memory addresses in x86_64 registers. Tagged numbers for counting stuff. Just look at off_t in Linux. Or unix filesescriptor fd numbers into a tiny per-process table of each Linux process. Some with hardware support, some without.

And then stuff like ptrdiff_t in the C abstract machine.

All the same idea. And it "only works", because they are "just numbers".

And then come the implementation details.

bryanlarsen 5 hours ago

Pointers have provenance, integers don't.

  • dotancohen 5 hours ago

    Go on.

    • bryanlarsen 5 hours ago

      I tried, but frankly, typing "pointer provenance" into Google gets you a much better explanation than my attempt. Google's AI analysis might be questionable, but it's less questionable than my first attempt.

      To oversimplify, provenance is the metadata a compiler keeps about a pointer during the compilation process.

      • c_engineer56 3 hours ago

        For example, Arm Memory Tagging Extension uses the top byte of a 64-bit address to store a tag that the CPU verifies against the allocation tag on pointer dereference. If the tags don't match, an exception occurs. MTE makes exploiting memory vulnerabilities more difficult by preventing the attacker from generating valid pointers to hijack program control flow with. To bypass MTE, the attack would need to combine the exploit with an info leak or arbitrary memory read to set the correct tag for a new pointer.

        On a MTE enabled system, adding an offset to a pointer cast to integer will result in an exception with high probability since the new pointer will be using the tag for the old address.

        https://docs.kernel.org/arch/arm64/memory-tagging-extension....

    • wat10000 2 hours ago
        int *x = malloc(4);
        *x = 42;
        int *y = realloc(x, 4);
        *y = 43;
        printf(“%p %d %p %d\n”, x, *x, y, *y);
      

      This may well print the same address for x and y while printing different values for x and y. Despite having the same bitwise value, x was invalidated by the call to realloc and it became illegal to access x. Thus the compiler is free to assume that x still holds the value previously assigned to it (or make demons fly out of your nose when you try to read from it), because a pointer isn’t just a memory address, it has meaning tied to where you got it and what you did with it.

  • dapperdrake 2 hours ago

    When you want to support something like Harvard architecture with functions in ROM and data in RAM.

  • afdbcreid 1 hour ago

    That is indeed the semantics most people want, but justifying why is not trivial, and it's also not trivial to formally specifying everything with this view.

pjmlp 6 hours ago

2018, and some of the comments are already outdated, SPARK 2014 is out there with ownership model.

  • dapperdrake 2 hours ago

    C abstract machine is from 1989 and also wants to be compatible with machines like a VAX or microcontrollers with Harvard architecture from back then.

    x86_64 is useful and widespread maybe because it is so easy to use like pointers are just integers and because the IBM PC was cheap back in the day and still is affordable today. And backwards compatibility just like Java.

    Itanium was not backwards compatible and died almost immediately.

    For better or for worse, C tries to run on all kinds of hardware that is obscure today. Like one's complement or sign-magnitude integers. This is why no C or C++ library will ever have decent bounds checked arrays.

    And back in 1989 it was decided that coming from a PDP-11 and faced with this "anything goes". Until compiler writers used UB to intentionally break SSL, everything looked fine. We are still learning from this.

    One problem with overflow safer languages on LLVM is that LLVM IR was originally designed for C++ and some NULL pointer UB weirdness or signed overflow weirdness specific to C was baked into LLVM's IR at the lowest level.

    As long as we do this it will be horrible. No escape hatch to sane behaviour. Except for people to skip all the UB by writing assembly for random proprietary microcontrollers.

jojogeo 4 hours ago

One is a mathematical construct, the other is a dog?

nico 1 hour ago

> What's the difference between an integer and a pointer?

This drove many people mad in college when learning C

And to be fair, sometimes tests seemed like they were trying to deliberately make us suffer

Conceptually they seem pretty clear (value vs link/reference). I think most of the confusion arrises when implementing, C can be hard to read and cryptic to follow when running. A debugger is almost always needed for anything but the most basic projects

I wonder if the hello world for C should actually include debugging instructions

  • mystifyingpoi 1 hour ago

    > Conceptually they seem pretty clear

    Well because they teach them wrong. Stepping through some examples with a debugger that shows all the values live should clear it up. And yes, use x86 as the teaching platform and ignore everything else, whoever is interested in some funky architectures will find the answers themselves after the class.

    > sometimes tests seemed like they were trying to deliberately make us suffer

    Half of it is because some teachers are pricks, but the other half is, that tests are meant to challenge someone's thinking. Being able to understand crap like int** x = &(*y) is absolutely useless in practice, but proves the knowledge that isn't just monkey memorizing.

glitchc 5 hours ago

I don't think GCC is doing something special, rather that -O3 might be optimizing out the subtraction. Try with -O0, I suspect you will get the same result as clang.

  • 8-prime 5 hours ago

    The GCC compiler changes the order of the operations such that the assignment happens after the print for x.

    call __printf_chk@PLT mov ecx, DWORD PTR 0[rbp] mov rdx, rbp mov edi, 2 mov DWORD PTR -96[rbx], 7

  • mkarrmann 5 hours ago

    The "special" thing of note is that GCC considers it acceptable to change the semantics of this program depending on the optimization level.

    • wat10000 4 hours ago

      That depends entirely on how you define “the semantics.” Any optimizing compiler has to draw a line between what the program is meant to do and how the emitted code actually makes it happen. The proper location of that line is not obvious. Can it turn x++,x++ into x+=2? That’s normally fine, potentially disastrous if x is a memory mapped register on an external device.

      C and C++ happen to have a particularly restrictive view on what “the semantics” of a program really are, such that there are a lot of things you can write in syntactically-legal C that officially erase the semantic meaning of the code. Within that definition of the program’s semantics, gcc’s optimizer is not supposed to change them, and any such change would be a bug. You’re taking a more expansive view of program semantics than the actual language specifies. If you do that, then any optimizing compiler is going to consider it to be acceptable to violate your special bespoke definition of them.

      • marcosdumay 4 hours ago

        > The proper location of that line is not obvious.

        If that's true, you have a bad language.

        What is known to be the case with C, but this is not a desirable nor a necessary state of affairs. A language can and should have defined semantics.

        • wat10000 2 hours ago

          I’m not talking about whether a language has defined semantics. C’s semantics are plenty well defined, much better than the current crop of more modern languages that are mostly defined by their single implementation.

          I’m talking about the question of what should be covered by the official semantics. That’s inherently subjective and a matter of opinion.

          Gcc’s optimizer does not accept changing language-level semantics based on which optimizations are performed. That the above comment thinks it does means that the commenter has a different notion of what should count as “the semantics” from what the language spec says. Which is a perfectly legitimate opinion, but if you take that position then you have to accept that other people will have other ideas of what should count, and therefore any optimizer might change “the semantics” of code according to at least some of those ideas.

      • oriolid 2 hours ago

        > Can it turn x++,x++ into x+=2

        For this particular example the line should be clear. If the variable is volatile, memory access can't be removed or reordered. If it's not volatile, everything is fair game.

        Mandatory Godbolt link: https://godbolt.org/z/fjKs4hbjo

        • wat10000 2 hours ago

          It’s clear by the language spec. It’s not clear based on how people want it to work or think it should work. And the inevitable stream of comments complaining about C compiler optimizers every time this gets discussed tells us that people are not willing to just consider where the language spec draws the line.

      • dapperdrake 2 hours ago

        More like code that falls through might be reordered in the binary and the C abstract machine has no concept of that.

        Or strange issues with optimizing infinite loops and the Halting problem preventing a full automated solution.

        The C compilers like GCC just hide stuff away and break things silently.

        • wat10000 1 hour ago

          Because doing so doesn’t change the semantics of the program as defined by the language.

          If you open the possibility of other notions of “the semantics” besides what the language spec lays out, then changing those semantics is an inherent part of an optimizer.

          What people (IMO fairly reasonably) want is a different C language spec with less undefined behavior and compilers that follow that spec. But people don’t think about it clearly and skip major parts of that picture when complaining about it.

m00dy 5 hours ago

range of values

cowlevel 5 hours ago

> First, does this C program execute undefined behavior? It does not! Computing out-of-bounds pointers is UB but we are free to do whatever we like with integer-typed values that were derived from pointers. Second, does the C standard mandate the behavior that we saw here? It does not!

Behaviour that is not defined is undefined behaviour. Integer to pointer conversion is IDB, which is the same as UB except that a conforming compiler documents what could happen. I believe it's typically documented as unpredictable, so the same as plain UB.

  • saagarjha 5 hours ago

    No, these are different things.

  • tsimionescu 4 hours ago

    There is a vast difference between IDB and UB. IDB is perfectly fine to rely on for your compiler, but it means your program may not be portable to other compilers.

    UB means your program is not a C program and has no semantics whatsoever past the point it reaches the UB. The compiler is thus free to assume that the point that the UB would happen can't be reached and optimize in accordance to that assumption - which many modern compilers do, with often unexpected consequences (such as the infamous case of removing an integer overflow check in Linux because an_int+1>an_int is guaranteed to be true in the C abstract model).

    • cowlevel 4 hours ago

      How does gcc document integer to pointer conversion?

      • Maxatar 4 hours ago
        • cowlevel 4 hours 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).

          • sham1 3 hours ago

            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.

spwa4 5 hours ago

There is no difference.

Yes, I'm a C programmer, how did you know?

  • Ohentis 5 hours ago

    It doesn't sound like you are or you would know C doesn't define either precisely enough to make that statement true.

    • Maxatar 4 hours ago

      On the contrary, the vast majority of C programmers don't know C well enough to understand the difference between integers and pointers.

      Using a tool doesn't mean understanding that tool, just means you know how to follow some repetitive processes over and over again.

    • kevin_thibedeau 4 hours ago

      They are definitely not integers on the Symbolics Lisp machine. The C standard allows for atypical representations. [u]intptr_t is optional for this reason.

      • cryptonector 3 hours ago

        Sure, but if you're not an embedded programmer, if you're not working with odd architectures, then the difference between pointers and unsigned integers of the same size in C on common current platforms' C ABIs, is minimal. Of course there are footguns here: you can't conjure up and dereference a pointer from an integer that isn't itself obtained from casting from a valid pointer.

  • Ungh 5 hours ago

    There's the voice of a C programmer who hasn't used hardware with a different word size to address space...

    • AnimalMuppet 4 hours ago

      But (almost) every hardware has some integer type that has the same size as what is needed to represent the address space, because (almost) every hardware has some way of manipulating addresses at the assembly level, and (almost) every C implementation has some integer type that generates those assembly instructions.

      I say "almost" because I am not absolutely certain that this is true of absolutely every architecture. Feel free to point out one that breaks these rules, if there is one.

      • Ungh 3 hours ago

        Segmented 8086 is always the fun one.

        • dhosek 2 hours ago

          I still have occasional nightmares about that. Once I got a 32-bit C/C++ compiler for DOS, I never looked back.

      • cryptonector 3 hours ago

        In principle a pointer can be a tuple of two other things. Think of CHERI, segmented architectures, etc. In practice on current, modern, general purpose, non-embedded platforms' C ABIs pointers are equivalent to unsigned integers of the same size.

        • sparkie 2 hours ago

          Arguably they're more like signed integers in the case of amd64 - due to address canonicalization. Eg, with 4-level paging we have a 48-bit address space, and valid pointers have the signed integer values `-2^48..+2^48-1`.

          They can be further complicated by UAI/LAM, which relaxes the canonicalization constraints and allows bits 48..62 (the high bits, excluding the sign bit) to be anything - so we can have pointers that compare unequal but point to the same address - a potential source of exploits (There's already been Spectre-like vulnerabilities shown for LAM). Fortunately nobody really uses LAM - it needs enabling by the kernel to be used in user space to begin with.

          • cryptonector 1 hour ago

            You don't need to interpret the high bit as a sign bit. uintptr_t (unsigned) shows we can interpret pointers as unsigned integers when we can interpret them as integers at all.

            • sparkie 1 hour ago

              You can interpret it as uintptr_t - particularly now that the latest C standards require two's complement representation of integers - but pointers on amd64 are more like signed ints.

              The sign bit must match the highest bit of the virtual address (47th bit counting from 0 in the case of 4LP, or the 56th bit for 5LP). (And without LAM/UAI, all the bits in between must match too.)

              Eg, with 4LP, if you cast a pointer to `uintptr_t`, shift it left 16 bits, then shift right 16 bits - then an address in the higher half (usually in the Kernel) would be non-canonical. Do the same for `intptr_t` it will be canonical because the shift right is an arithmetic shift.

              On other architectures this isn't the case. I know AARCH64 for example does not use canonicalization. If you were doing the same shift left/right by 16 as above on AARCH64, you'd want a uintptr_t.

  • yxhuvud 5 hours ago

    There is a counter example in the OP.

  • coolius 4 hours ago

    I agree, I have passed void* to the JVM by casting to int more often than I can count

  • HarHarVeryFunny 3 hours ago

    C doesn't provide any guarantee that a pointer can be stored in an integer.

    The language only guarantees that an integer is at least 16 bits. There is no guarantee that a compiler that supports a > 16 bit address space will chose to make integers large enough to hold a pointer, and for example gcc still uses 32-bit integers for 64-bit processors.

    I'm not sure if C even requires a pointer to be just a linear address, as opposed to something structured.

    • sparkie 2 hours ago

      > I'm not sure if C even requires a pointer to be just a linear address, as opposed to something structured.

      It doesn't. The standard does not require any particular representation for pointers. It does specify that addition and subtraction on them is possible - but does not specify how this occurs - only that for example, if you have an array `int x[]`, then `x + 1` should point to the second item (index 1) in the array.