I wanted to ask, is dynamically creating a pointer, and then changing a pointer address to something else still deleting the original allocated space?
for example:
int main()
{
int c = 50;
// Memory leak
int * q = new int;
q = & c;
delete q;
}
What exactly is getting deleted or happening?
Thanks!
Delete is an operator that is used to destroy array and non-array(pointer) objects which are created by new expression. New operator is used for dynamic memory allocation which puts variables on heap memory.
You don't need to delete it, and, moreover, you shouldn't delete it. If earth is an automatic object, it will be freed automatically. So by manually deleting a pointer to it, you go into undefined behavior. Only delete what you allocate with new .
You usually delete the object that a pointer is pointing to, rather than the pointer itself. You can do this using the “delete” keyword if the object was allocated using the “new” keyword, otherwise if the memory was allocated using malloc(), you would need to call the free() function.
It is not safe to delete a void pointer in C/C++ because delete needs to call the destructor of whatever object it's destroying, and it is impossible to do that if it doesn't know the type.
What exactly is getting deleted or happening?
Memory leaking and undefined behaviour.
When you do q = & c;
you are losing your only tracking of the memory allocated by new int
. Noone keeps track of this for you, there is no garbage collector, it is simply lost and cannot be recovered.
When you then do delete q;
(where q
is assigned to &c
) you are deleting memory that you didn't allocate, and worse you are deleting memory on the stack. Either of these will result in undefined behavior.
This is an excellent preface into why you should avoid using pointers in circumstances where you don't need them. In this case, there is no reason dynamically allocate your int
. If you really need a pointer, use a c++11
smart pointer (or boost
if you don't have c++11
). There are increasingly rare cases where you really do need a raw c
type pointer. You should read Effective Modern c++ Chapter 4 for excellent detail on this subject.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With