Reputation: 73
If you do the following:
ClassType *foo = new ClassType();
ClassType *moo = foo;
delete foo;
And then move along, are there still dangling pointers or not? I thought no, because you only declared one "new", and deleted it, but I want to be sure...
Thanks
Upvotes: 0
Views: 200
Reputation: 1153
In C++, the delete
operator calls the destructor of the given argument, and returns memory allocated by new
back to the heap. Period. It does nothing more which would mean your pointers that were pointing to a location on the heap, just point to that memory location which has just been de-allocated. So those pointer variables still contain those addresses which it was previously pointing to. This is called 'Dangling pointer'. Now if you assign your - moo
and foo
to NULL
after delete
, you will be able to identify if your pointers point to a valid location or NULL easily.
Upvotes: 2
Reputation: 30035
You created one object and deleted it. Both your pointers still point to the memory address that was previously occupied by that object, but the object is deleted, and generally this is the accepted definition of a dangling pointer - one that points to some memory that no longer contains an active object.
There is no memory leak, and your program doesn't cause a problem unless you try to access the now-deleted object through either of your pointers.
Using something like std::shared_ptr or std::unique_ptr may help you manage the memory in a safer way.
Upvotes: 3
Reputation: 720
foo and moo points on the same dynamic object, created with:
ClassType *foo = new ClassType();
So if you delete foo also moo is 'deleted' or it become an empty pointer.
Upvotes: -1
Reputation: 4663
If you mean Dangling pointers, yes the pointers moo
and foo
are invalid now since it points to something which is already deleted.
Upvotes: 1