Home >Backend Development >C++ >Is Dereferencing an Uninitialized Pointer in C Undefined Behavior?

Is Dereferencing an Uninitialized Pointer in C Undefined Behavior?

Susan Sarandon
Susan SarandonOriginal
2024-12-14 14:52:16612browse

Is Dereferencing an Uninitialized Pointer in C   Undefined Behavior?

Undefined Behavior: Dereferencing Uninitialized Pointers in C

A common point of confusion in C is understanding when dereferencing an uninitialized pointer constitutes undefined behavior (UB). While the C standard contains numerous rules, it can be challenging to locate the exact provisions that define this behavior.

The code snippet in question:

int* ptr;
*ptr = 0;

raises the question of whether dereferencing ptr leads to UB. To clarify this, we'll delve into the pertinent sections of the C standard.

Standard Provisions

Section 4.1 of the standard provides crucial insight. It states that:

"If the object to which the lvalue refers is not an object of type T and is not an object of a type derived from T, or if the object is uninitialized, a program that necessitates this conversion has undefined behavior."

In our case, ptr is an uninitialized pointer to an integer. Thus, attempting to dereference it without initializing it first falls under the condition described in Section 4.1 and results in UB.

Section 3.7.3.2/4, often cited in relation to UB, does not apply directly to the code snippet in question as it pertains to using deallocation functions on non-null pointers.

Additional Resources

Searching for "uninitial" in the standard can reveal other relevant sections, such as 8.5.1, which further clarifies the rules for accessing uninitialized objects.

The above is the detailed content of Is Dereferencing an Uninitialized Pointer in C 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