Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting Pointers

Tags:

c++

pointers

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!

like image 776
anon anon Avatar asked Feb 22 '18 04:02

anon anon


People also ask

What does deleting a pointer do?

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.

Do you have to delete pointers?

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 .

How do you remove a pointer from a pointer?

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.

Can we delete the pointer in C?

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.


1 Answers

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.

like image 58
Fantastic Mr Fox Avatar answered Oct 19 '22 05:10

Fantastic Mr Fox