Home  >  Article  >  Backend Development  >  What Happens to Pointers After Deleting the Memory They Point To in C ?

What Happens to Pointers After Deleting the Memory They Point To in C ?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-01 01:48:02993browse

What Happens to Pointers After Deleting the Memory They Point To in C  ?

Pointers Behavior in C after Delete

In C , deleting a pointer deallocates the memory it points to. However, the behavior of pointers pointing to that deleted memory becomes undefined or implementation-defined, depending on the C version.

Consider the following code:

<code class="cpp">A* a = new A();
A* b = a;

delete a;

A* c = a; // Assuming undefined or implementation-defined in C++11
A* d = b; // Supposed to be legal</code>

Reading Value of Copy of Deleted Pointer (b)

In C 11, reading the value of b after a has been deleted is undefined behavior. However, in C 14, it is implementation-defined. This is because the pointer b itself becomes an "invalid pointer value" after a is deleted.

Implementation-Defined Behavior

In C 14, using an invalid pointer value, including copying it, has implementation-defined behavior. This means the compiler is allowed to decide what to do in such cases. In some implementations, it may generate a runtime fault, while in others, it may allow the operation but result in undefined behavior when the pointer is subsequently used.

Legal or Undefined?

Therefore, both A* c = a; and A* d = b; are undefined in C 11 and implementation-defined in C 14. The copied pointer value (b) is considered an invalid pointer value, and its use is subject to the implementation's definition.

The above is the detailed content of What Happens to Pointers After Deleting the Memory They Point To in C ?. 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