Rationale for pointer comparisons outside an array to be UB

后端 未结 4 653
一向
一向 2020-12-10 07:30

So, the standard (referring to N1570) says the following about comparing pointers:

C99 6.5.8/5 Relational operators

When two pointers are

4条回答
  •  鱼传尺愫
    2020-12-10 07:35

    The 8086 is a processor with 16 bit registers and a 20 bit address space. To cope with the lack of bits in its registers, a set of segment registers exists. On memory access, the dereferenced address is computed like this:

    address = 16 * segment + register
    

    Notice that among other things, an address has generally multiple ways to be represented. Comparing two arbitrary addresses is tedious as the compiler has to first normalize both addresses and then compare the normalized addresses.

    Many compilers specify (in the memory models where this is possible) that when doing pointer arithmetic, the segment part is to be left untouched. This has several consequences:

    • objects can have a size of at most 64 kB
    • all addresses in an object have the same segment part
    • comparing addresses in an object can be done just by comparing the register part; that can be done in a single instruction

    This fast comparison of course only works when the pointers are derived from the same base-address, which is one of the reasons why the C standard defines pointer comparisons only for when both pointers point into the same object.

    If you want a well-ordered comparison for all pointers, consider converting the pointers to uintptr_t values first.

提交回复
热议问题