Double Deletion and Its Consequence
Double deletion is an error that occurs when a pointer is deleted twice. This can result in undefined behavior, meaning that anything can happen, including a runtime crash.
In the code snippet provided:
Obj *op = new Obj; Obj *op2 = op; delete op; delete op2;
The object op is created using the new operator. Then, a second pointer op2 is created pointing to the same object. When op is deleted, the object's memory is freed. However, when op2 is deleted, the same memory is freed again, leading to double deletion.
The consequences of double deletion can be severe. Since the memory has already been freed, accessing the object pointed to by op2 after the first deletion will result in unexpected behavior. This can lead to undefined behavior, segmentation faults, or other runtime errors.
The compiler will not throw an error in this instance because the errors only occur at runtime when the program attempts to access the already-deleted memory. To avoid double deletion, it's crucial to ensure that a pointer is only deleted once.
The above is the detailed content of What Happens When You Double Delete a Pointer in C ?. For more information, please follow other related articles on the PHP Chinese website!