Home  >  Article  >  Backend Development  >  What Happens to Pointers Referencing the Same Object After One is Deleted in C ?

What Happens to Pointers Referencing the Same Object After One is Deleted in C ?

Susan Sarandon
Susan SarandonOriginal
2024-11-01 11:29:30758browse

What Happens to Pointers Referencing the Same Object After One is Deleted in C  ?

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:

  • Assigning to c from the previously deleted pointer a causes undefined behavior since a is now an invalid pointer value.
  • However, d points to a copy of a made before the deletion. Although reading the value of b points to a deallocated memory location, this action is implementation-defined.

C 14 Behavior:

  • Assigning to both c and d from the invalid pointer a still causes undefined behavior.
  • Copying the value of an invalid pointer, as done here with b, is also implementation-defined 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!

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