Home > Article > Backend Development > Is using a pointer derived from a deleted pointer valid in C ?
Pointers After delete in C : The Perplexing Case of a and b
In the world of C pointers, the act of deleting an allocated memory through delete raises questions about the validity of pointers pointing to that memory. Consider the following scenario:
<code class="cpp">A* a = new A(); A* b = a; delete a; A* c = a; // illegal in C++11 A* d = b; // legal?</code>
The crux of the question lies in determining the validity of using the value of the pointer b after a has been deleted.
The Fate of Invalid Pointers: Undefined Behavior in C 11, Implementation-Defined in C 14
In C 11, accessing the value of a deleted pointer (a) results in undefined behavior. However, the usage of a pointer (b) that was derived from the deleted pointer presents a nuanced situation.
Under C 11, both c = a; and d = b; are deemed undefined behavior. This is because both a and b are considered "invalid pointer values" as they point to deallocated storage. Any attempt to perform operations on invalid pointers is explicitly undefined.
Implementation-Defined Intricacies in C 14
C 14 introduces subtle changes to this scenario. According to the revised standard, "using an invalid pointer value" includes "copying the value of." Therefore, in C 14, both assignments to c and d are considered implementation-defined.
The reason behind this change is that copying an invalid pointer value could potentially trigger a runtime fault on certain implementations. The standard wisely leaves it up to the implementation to handle such cases as it sees fit.
In conclusion, the legality of using b after a has been deleted hinges on the C version being used. C 11 deems both c = a; and d = b; undefined behavior, while C 14 shifts the responsibility to the implementation, leaving the outcome unspecified in the standard.
The above is the detailed content of Is using a pointer derived from a deleted pointer valid in C ?. For more information, please follow other related articles on the PHP Chinese website!