Home > Backend Development > C++ > 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
Release: 2024-11-01 01:48:02
Original
1079 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template