Do C and C++ standards imply that a special value in the address space must exist solely to represent the value of null pointers?

后端 未结 4 1516
猫巷女王i
猫巷女王i 2021-01-27 08:08

Following discussion from this question about null pointers in C and C++, I\'d like to have the ending question separated here.

If it can be inferred from C and C++ stan

4条回答
  •  故里飘歌
    2021-01-27 08:13

    That depends on what is meant by the phrase "address space". The C standard uses the phrase informally, but doesn't define what it means.

    For each pointer type, there must be a value (the null pointer) that compares unequal to a pointer to any object or function. That means, for example, that if a pointer type is 32 bits wide, then there can be at most 232-1 valid non-null values of that type. There could be fewer than that if some addresses have more than one representation, or if not all representations correspond to valid addresses.

    So if you define the "address space" to cover 2N distinct addresses, where N is the width in bits of a pointer, then yes, one of those values must be reserved as the null pointer value.

    On the other hand, if the "address space" is narrower than that (for example, typical 64-bit systems can't actually access 264 distinct memory locations), then the value reserved as the null pointer can easily be outside the "address space".

    Some things to note:

    • The representation of a null pointer may or may not be all-bits-zero.
    • Not all pointer types are necessarily the same size.
    • Not all pointer types necessarily use the same representation for a null pointer.

    On most modern implementations, all pointer types are the same size, and all represent a null pointer as all-bits-zero, but there are valid reasons to, for example, make function pointers wider than object pointers, or make void* wider than int*, or use a representation other than all-bits-zero for the null pointer.

    This answer is based on the C standard. Most of it also applies to C++. (One difference is that C++ has pointer-to-member types, which are typically wider than ordinary pointers.)

提交回复
热议问题