Home  >  Article  >  Backend Development  >  Is Storing an Invalid Pointer Address Undefined Behavior?

Is Storing an Invalid Pointer Address Undefined Behavior?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-26 10:08:03363browse

Is Storing an Invalid Pointer Address Undefined Behavior?

Storing an Invalid Pointer

While it is well-established that dereferencing an invalid pointer leads to undefined behavior, a less clear question arises: is the act of storing an invalid memory address in a pointer variable itself undefined behavior?

Consider the following code snippet:

<code class="c++">const char* str = "abcdef";
const char* begin = str;
if (begin - 1 < str) { /* ... do something ... */ }</code>

In this example, the expression begin - 1 evaluates to an invalid memory address. However, the address is not explicitly dereferenced but rather used in pointer arithmetic to determine its validity.

Is this scenario considered undefined behavior?

Intuitively, some may argue that it is not, since pointer arithmetic often hinges on such operations. Additionally, pointers are inherently integers. However, it has been asserted that even the mere act of storing an invalid pointer into a register can be undefined behavior due to potential architectural implications (e.g., bus errors).

To clarify this matter, we turn to the relevant C or C standards. Unfortunately, this issue remains unresolved by omission. Section 6.5.6/8 of the C Draft Standard outlines the semantics of pointer arithmetic when the pointer points to an array element and the array is sufficiently large or when the operand points one past the last array element. The behavior in the situation described above does not fall within these specific cases. Therefore, storing an invalid pointer is by omission undefined behavior.

The above is the detailed content of Is Storing an Invalid Pointer Address Undefined Behavior?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn