Home  >  Article  >  Backend Development  >  What Happens to Copied Pointers in C After the Original is Deleted?

What Happens to Copied Pointers in C After the Original is Deleted?

DDD
DDDOriginal
2024-11-01 15:13:02279browse

What Happens to Copied Pointers in C   After the Original is Deleted?

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!

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