Skip to content

Valid Pointers and related

Jeff Hammond edited this page Dec 21, 2022 · 1 revision

This page exists to discuss the topic of valid pointers, which is motivated by https://github.com/mpiwg-abi/abi-issues/issues/3.

References

C++17 (draft) - ISO/IEC DIS 14882:2017(E) N4660

6.7 Storage duration [basic.stc]

When the end of the duration of a region of storage is reached, the values of all pointers representing the address of any part of that region of storage become invalid pointer values (6.9.2). Indirection through an invalid pointer value and passing an invalid pointer value to a deallocation function have undefined behavior. Any other use of an invalid pointer value has implementation-defined behavior. 37

  1. Some implementations might define that copying an invalid pointer value causes a system-generated runtime fault.

SEI CERT C Coding Standard

Invalid Pointer

invalid pointer

A pointer that is not a valid pointer.

Valid Pointer

valid pointer [ISO/IEC TS 17961:2013]

Pointer that refers to an element within an array or one past the last element of an array. See invalid pointer.

NOTE

For the purposes of this definition, a pointer to an object that is not an element of an array behaves the same as a pointer to the first element of an array of length one with the type of the object as its element type. (See C Standard, 6.5.8, paragraph 4.)

For the purposes of this definition, an object can be considered to be an array of a certain number of bytes; that number is the size of the object as produced by the sizeof operator. (See C Standard, 6.3.2.3, paragraph 7.)

Converting a pointer to integer or integer to pointer

Noncompliant Code Example

It is sometimes necessary to access memory at a specific location, requiring a literal integer to pointer conversion. In this noncompliant code, a pointer is set directly to an integer constant, where it is unknown whether the result will be as intended:

unsigned int *g(void) {
  unsigned int *ptr = 0xdeadbeef;
  /* ... */
  return ptr;
}

The result of this assignment is implementation-defined, might not be correctly aligned, might not point to an entity of the referenced type, and might be a trap representation.

Compliant Solution

Unfortunately this code cannot be made safe while strictly conforming to ISO C.

A particular platform (that is, hardware, operating system, compiler, and Standard C library) might guarantee that a memory address is correctly aligned for the pointer type, and actually contains a value for that type. A common practice is to use addresses that are known to point to hardware that provides valid values.