Pointers to Released Memory in C
After deleting a pointer, confusion arises regarding the validity of other pointers referencing the same object. This article aims to clarify this behavior in C .
Consider the following code:
<code class="cpp">A* a = new A(); A* b = a; delete a; A* c = a; // Illegal (C++11) A* d = b; // Debatable legality // Points to deallocated memory, Undefined in C++11 A* aAddr = &a;</code>
C 11 Behavior:
C 14 Behavior:
According to the C 11 standard, using an invalid pointer value (including copying it) causes undefined behavior. In C 14, such operations have implementation-defined behavior, meaning the behavior may vary across different compilers and operating systems.
Therefore, in both C 11 and C 14, it is critical to avoid using pointers that have been deleted or refer to deallocated memory. Doing so can lead to unpredictable and potentially erroneous behavior.
The above is the detailed content of What Happens to Pointers Referencing the Same Object After One is Deleted in C ?. For more information, please follow other related articles on the PHP Chinese website!