This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Undefined, unspecified and implementation-defined behavior
I know calling delete on same object is disastrous. But that is true as long as the memory is not reallocated for some other object before the second call to delete. But, even doing the below is wrong? If I remove the cout, the code is not dumping core.
int main()
{
A *a1 = new A();
delete a1;
cout<<a1<<endl;
delete a1;
}
See What happens in a double delete?:
Yes, it is very wrong.
The big problem is that the behavior is undefined. So it you might get away with it in one situation on one compiler, but in general it tends to cause a crash.
Related
This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
C++ delete - It deletes my objects but I can still access the data?
(13 answers)
Closed 4 years ago.
#include<iostream>
#include<conio.h>
using namespace std;
class Marie{
public:
int x;
Marie(){
cout<<"created";
}
~Marie(){
cout<<"hii i am destructor";
}
void ShowMarie() {
cout<<"friends";
x=5;
delete this; /*<--- here destructor called */
}
};
int main(){
Marie *ptr = new Marie;
ptr->ShowMarie();
cout<<ptr->x; /*<---- ptr is dangling pointer but it is still showing me the correct value.*/
getch();
}
After calling the destructor for the object, it's still referencing as if it is in the memory? why?
And why do we need to call the destructor explicitly for a dynamically created object by using delete this?
If we use delete this; inside destructor what will happen? Is this making the call to destructor recursively?
After calling the destructor for the object, it's still referencing as
if it is in the memory? why?
https://stackoverflow.com/a/16102870/7906416
https://stackoverflow.com/a/7827569/7906416
Deleting a pointer doesn't zero out any memory because to do so would take CPU cycles and that's not what C++ is about. What you have there is a dangling pointer, and potentially a subtle error ... (Benj answer).
And why do we need to call the destructor explicitly for a dynamically
created object by using delete this?
https://stackoverflow.com/a/14187068/7906416
Calling the destructor manually is required if the object was constructed using an overloaded form of operator new(), except when using the "std::nothrow" overloads... (Dietmar Kühl answer).
If we use delete this; inside destructor what will happen? Is this
making the call to destructor recursively?
https://stackoverflow.com/a/3063401/7906416
As soon as the destructor is called (the first time), the lifetime of the object has ended. Thus, if you call the destructor for the object from within the destructor, the behavior is undefined ... (James McNellis answer).
Please in your future search(es) use the stackoverflow database, most of the time there is already an answer to your question.
Dereferencing a deleted pointer is undefined behaviour. In your example, it just happens that the memory where the object pointed by ptr hasn't been overwritten thus, it is still in the memory.
When creating an object dynamically, you are reserving that memory and it will remain reserved till you reclaim it using delete.
My best guess is that yes, it will call the destructor recursively till there is a stack overflow.
This question already has answers here:
delete vs delete[] operators in C++
(7 answers)
Closed 4 years ago.
This may sound a bit strange, but if I have the code uses delete [] as follows:
int main()
{
int *test = new int(5);
delete [] test //Does this work?
// delete test (This is the standard syntax)
}
Of course, I tried to compile and run, and delete [] didn't return any errors. According to http://www.cplusplus.com/reference/new/operator%20delete[]/, delete[] operator first calls the appropriate destructors for each element in the array (if these are of a class type), and then calls an array deallocation function. I'm not 100% sure what array deallocation function is, but I presume this will not cause memory leak?
Running delete [] for a pointer which was allocated with new is an undefined behavior. It may work, or may not, or may stop working at any moment, or may ruin your hardware. You have no guarantee.
This question already has answers here:
Deleting a heap then dereferencing a pointer to that memory
(4 answers)
Closed 6 years ago.
I am reading Learning a New Programming Language: C++ for Java Programmers here, and there is an example on pointers that reads:
Never dereference a dangling pointer (a pointer to a location that was pointed to by another pointer that has been deleted):
int *p, *q;
p = new int;
q = p; // p and q point to the same location
delete q; // now p is a dangling pointer
*p = 3; // bad!
However, if I copy this code into a main function and add the following cout:
cout << p << " " << *p << endl;
I get the output:
0000022DC3DD0EF0 3
Which seems valid to me, I get the pointer and then the deref'd value.
Is this a typo in the webpage, or is the above code bad practice?
This is undefined behavior. You cannot access memory through a deleted pointer. That is a coincidence.
When you delete object it's memory is marked as free and can be used by other objects or even returned to OS. But nobody wastes CPU for erasing the object from memory. So p is still there but it is not yours anymore. You can't be sure what is stored in that place or even that you still have right to read the memory.
Your example is very simple so it's behaviour is predictable. When there is much work done between removal of the object and accessing it's memory, things go weird. And what's worse, such bugs are floating, sometimes code works correctly and sometimes not. So they are hard to debug.
Which seems valid to me, I get the pointer and then the deref'd value.
Among the behaviors allowed by the term "undefined behavior" is to produce results that sucker you into thinking everything is fine. (and then stop working in a more complex program giving you lots of grief because you believe that this can't possibly be the problem)
This question already has answers here:
how to properly delete a pointer to array
(6 answers)
Closed 8 years ago.
Is this code legal?
int * a = new int[1];
delete a;
Or this one?
int * a = new int;
delete [] a;
Obviously, this doesn't seem right and should be discouraged at the very least but will it cause any actual problems (memory leaks and whatnot)?
Matching combination must be:-
new; delete;
new[]; delete[];
If you mix these up you would get undefined behaviour. I have seen code blowing up due to this.
No. If you new you should delete. And if you new[] you should delete[].
Mixing scalar and array (de)allocation operators leads to undefined behaviour. A defined difference between delete and delete[] is that the latter calls the destructors for all elements of the array.
http://www.cplusplus.com/reference/new/operator%20delete[]/
This question already has answers here:
Can a local variable's memory be accessed outside its scope?
(20 answers)
Closed 9 years ago.
I know that a dangling handle is a pointer or reference to invalid data. And I experiment with string and vector, below is my code with string:
char *p = NULL;
{
string s;
s.push_back('a');
s.push_back('b');
p = &s[0];
}
cout << *p << endl;
and the result is 'a'. It surprised me, shouldn't p be a dangling pointer? And I think that the object s should have been destructed, why can p still point to the valid content?
And I do another experiment with vector by just replacing the "string" with "vector" in the code above, and this time print nothing. So what does this mean? Is there any difference that string and vector organize their members?
You are invoking undefined behaviour, so anything can happen. In your case it just happens that the memory hasn’t been overwritten yet. It could also just segfault, wipe your harddrive or awaken the nasal demons.
Traffic laws say that if you wait for a green light, you are guaranteed to be able to cross the road safely.
You are complaining that not everyone who crosses at a red light is instantly crushed by a truck.