Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of valid pointer

In the comments to this answer I stumbled about a discussion about the meaning of "valid pointer". Since I think that that is interesting in general:

What is a "valid pointer" in C++?

In particular:

Is reinterpret_cast<const void*>(0x1) a valid pointer?

like image 396
Baum mit Augen Avatar asked Jun 25 '14 00:06

Baum mit Augen


People also ask

What is a valid pointer?

By the below code we can check if pointer valid or not if ( ptr->value == NULL ) { //pointer is invalid } else //pointer is valid. So if ptr-> value means we check if a value is assigned or not if it is not assigned means the memory is not given. So null it is an invalid pointer and hence we cannot use it.

Is 1 a valid pointer?

On some architectures, -1 is a legal pointer value. Some microcontrollers have RAM in the low part of memory, and read-only memory (like flash) in the upper parts.

What is an invalid pointer?

An invalid pointer reference occurs when a pointer's value is referenced even though the pointer doesn't point to a valid block. One way to create this error is to say p=q;, when q is uninitialized. The pointer p will then become uninitialized as well, and any reference to *p is an invalid pointer reference.

Is null a valid pointer?

NULL is by definition an invalid pointer.


1 Answers

The Standard places implementations into two general categories:

  • Those with strict pointer safety
  • Those with relaxed pointer safety

Your expression definitely is not a safely-derived pointer, so it's invalid in the first.

Quote from 3.7.4.3:

An implementation may have relaxed pointer safety, in which case the validity of a pointer value does not depend on whether it is a safely-derived pointer value. Alternatively, an implementation may have strict pointer safety, in which case a pointer value referring to an object with dynamic storage duration that is not a safely-derived pointer value is an invalid pointer value unless the referenced complete object has previously been declared reachable (20.7.4). [ Note: the effect of using an invalid pointer value (including passing it to a deallocation function) is undefined, see 3.7.4.2. This is true even if the unsafely-derived pointer value might compare equal to some safely-derived pointer value. — end note ] It is implementation defined whether an implementation has relaxed or strict pointer safety.

For implementations with relaxed safety, it doesn't matter how the pointer value is gotten, just that (3.9.2):

A valid value of an object pointer type represents either the address of a byte in memory (1.7) or a null pointer.

Is 0x1 a valid memory address on your system? Well, for some embedded systems it is. For most OSes using virtual memory, the page beginning at zero is reserved as invalid.

like image 189
Ben Voigt Avatar answered Sep 22 '22 11:09

Ben Voigt