Home  >  Article  >  Backend Development  >  ## Is Storing an Invalid Pointer Always Undefined Behavior in C/C ?

## Is Storing an Invalid Pointer Always Undefined Behavior in C/C ?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-26 02:34:27848browse

## Is Storing an Invalid Pointer Always Undefined Behavior in C/C  ?

Is Storing an Invalid Pointer Always Undefined Behavior?

In C and C , dereferencing an invalid pointer results in undefined behavior. However, a question arises: does merely storing an invalid memory address in a pointer variable constitute undefined behavior?

Consider the following code:

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

Here, the expression begin - 1 evaluates to an invalid memory address. While we refrain from dereferencing it, we utilize it in pointer arithmetic to determine its validity. So, does this operation entail undefined behavior, given that certain architectures may trigger a bus error upon loading an invalid pointer into a register?

The answer to this question lies within the C or C standard. According to the C Draft Standard, storing an invalid pointer is indeed undefined behavior. Section 6.5.6/8 of the standard defines pointer arithmetic, but it does not explicitly cover the case where the operand points to an invalid memory address.

Therefore, by omission, the C standard leaves this case unspecified, rendering it undefined behavior. Consequently, storing an invalid pointer in a pointer variable, even if it is not dereferenced, is considered undefined behavior in C and C according to the current standard.

The above is the detailed content of ## Is Storing an Invalid Pointer Always Undefined Behavior in C/C ?. 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