Pointers in C After Delete
Consider the following code snippet in C :
<code class="cpp">A* a = new A(); A* b = a; delete a; A* c = a; // Undefined behavior in C++11 A* d = b; // Potentially legal, but uncertain</code>
This code raises the question: what happens when accessing the value of a copied pointer after the original pointer has been deleted?
In C 11, accessing the value of a pointer that has been deleted leads to undefined behavior. This applies to both pointers a and b. Copying the value of a into c is also undefined, as a points to deallocated memory.
However, in C 14, the behavior becomes implementation-defined. The standard specifies that:
"Indirection through an invalid pointer value and passing an invalid pointer value to a deallocation function have undefined behavior. Any other use of an invalid pointer value has implementation-defined behavior."
Therefore, in C 14, accessing the value of b, which is a copy of a, is also implementation-defined. It could potentially lead to undefined behavior, but it may also be handled differently by specific implementations.
In summary, both A* c = a; and A* d = b; are undefined in C 11 and implementation-defined in C 14. This is because both pointers a and b point to invalid memory after the delete operation.
The above is the detailed content of What Happens to Copied Pointers in C After the Original is Deleted?. For more information, please follow other related articles on the PHP Chinese website!